cord.cc 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047
  1. // Copyright 2020 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/strings/cord.h"
  15. #include <algorithm>
  16. #include <atomic>
  17. #include <cstddef>
  18. #include <cstdio>
  19. #include <cstdlib>
  20. #include <iomanip>
  21. #include <iostream>
  22. #include <limits>
  23. #include <ostream>
  24. #include <sstream>
  25. #include <type_traits>
  26. #include <unordered_set>
  27. #include <vector>
  28. #include "absl/base/casts.h"
  29. #include "absl/base/internal/raw_logging.h"
  30. #include "absl/base/macros.h"
  31. #include "absl/base/port.h"
  32. #include "absl/container/fixed_array.h"
  33. #include "absl/container/inlined_vector.h"
  34. #include "absl/strings/escaping.h"
  35. #include "absl/strings/internal/cord_internal.h"
  36. #include "absl/strings/internal/cord_rep_btree.h"
  37. #include "absl/strings/internal/cord_rep_flat.h"
  38. #include "absl/strings/internal/cordz_statistics.h"
  39. #include "absl/strings/internal/cordz_update_scope.h"
  40. #include "absl/strings/internal/cordz_update_tracker.h"
  41. #include "absl/strings/internal/resize_uninitialized.h"
  42. #include "absl/strings/str_cat.h"
  43. #include "absl/strings/str_format.h"
  44. #include "absl/strings/str_join.h"
  45. #include "absl/strings/string_view.h"
  46. namespace absl {
  47. ABSL_NAMESPACE_BEGIN
  48. using ::absl::cord_internal::CordRep;
  49. using ::absl::cord_internal::CordRepBtree;
  50. using ::absl::cord_internal::CordRepConcat;
  51. using ::absl::cord_internal::CordRepExternal;
  52. using ::absl::cord_internal::CordRepFlat;
  53. using ::absl::cord_internal::CordRepSubstring;
  54. using ::absl::cord_internal::CordzUpdateTracker;
  55. using ::absl::cord_internal::InlineData;
  56. using ::absl::cord_internal::kMaxFlatLength;
  57. using ::absl::cord_internal::kMinFlatLength;
  58. using ::absl::cord_internal::kInlinedVectorSize;
  59. using ::absl::cord_internal::kMaxBytesToCopy;
  60. constexpr uint64_t Fibonacci(unsigned char n, uint64_t a = 0, uint64_t b = 1) {
  61. return n == 0 ? a : Fibonacci(n - 1, b, a + b);
  62. }
  63. static_assert(Fibonacci(63) == 6557470319842,
  64. "Fibonacci values computed incorrectly");
  65. // Minimum length required for a given depth tree -- a tree is considered
  66. // balanced if
  67. // length(t) >= min_length[depth(t)]
  68. // The root node depth is allowed to become twice as large to reduce rebalancing
  69. // for larger strings (see IsRootBalanced).
  70. static constexpr uint64_t min_length[] = {
  71. Fibonacci(2), Fibonacci(3), Fibonacci(4), Fibonacci(5),
  72. Fibonacci(6), Fibonacci(7), Fibonacci(8), Fibonacci(9),
  73. Fibonacci(10), Fibonacci(11), Fibonacci(12), Fibonacci(13),
  74. Fibonacci(14), Fibonacci(15), Fibonacci(16), Fibonacci(17),
  75. Fibonacci(18), Fibonacci(19), Fibonacci(20), Fibonacci(21),
  76. Fibonacci(22), Fibonacci(23), Fibonacci(24), Fibonacci(25),
  77. Fibonacci(26), Fibonacci(27), Fibonacci(28), Fibonacci(29),
  78. Fibonacci(30), Fibonacci(31), Fibonacci(32), Fibonacci(33),
  79. Fibonacci(34), Fibonacci(35), Fibonacci(36), Fibonacci(37),
  80. Fibonacci(38), Fibonacci(39), Fibonacci(40), Fibonacci(41),
  81. Fibonacci(42), Fibonacci(43), Fibonacci(44), Fibonacci(45),
  82. Fibonacci(46), Fibonacci(47),
  83. 0xffffffffffffffffull, // Avoid overflow
  84. };
  85. static const int kMinLengthSize = ABSL_ARRAYSIZE(min_length);
  86. static inline bool btree_enabled() {
  87. return cord_internal::cord_btree_enabled.load(
  88. std::memory_order_relaxed);
  89. }
  90. static inline bool IsRootBalanced(CordRep* node) {
  91. if (!node->IsConcat()) {
  92. return true;
  93. } else if (node->concat()->depth() <= 15) {
  94. return true;
  95. } else if (node->concat()->depth() > kMinLengthSize) {
  96. return false;
  97. } else {
  98. // Allow depth to become twice as large as implied by fibonacci rule to
  99. // reduce rebalancing for larger strings.
  100. return (node->length >= min_length[node->concat()->depth() / 2]);
  101. }
  102. }
  103. static CordRep* Rebalance(CordRep* node);
  104. static void DumpNode(CordRep* rep, bool include_data, std::ostream* os,
  105. int indent = 0);
  106. static bool VerifyNode(CordRep* root, CordRep* start_node,
  107. bool full_validation);
  108. static inline CordRep* VerifyTree(CordRep* node) {
  109. // Verification is expensive, so only do it in debug mode.
  110. // Even in debug mode we normally do only light validation.
  111. // If you are debugging Cord itself, you should define the
  112. // macro EXTRA_CORD_VALIDATION, e.g. by adding
  113. // --copt=-DEXTRA_CORD_VALIDATION to the blaze line.
  114. #ifdef EXTRA_CORD_VALIDATION
  115. assert(node == nullptr || VerifyNode(node, node, /*full_validation=*/true));
  116. #else // EXTRA_CORD_VALIDATION
  117. assert(node == nullptr || VerifyNode(node, node, /*full_validation=*/false));
  118. #endif // EXTRA_CORD_VALIDATION
  119. static_cast<void>(&VerifyNode);
  120. return node;
  121. }
  122. // Return the depth of a node
  123. static int Depth(const CordRep* rep) {
  124. if (rep->IsConcat()) {
  125. return rep->concat()->depth();
  126. } else {
  127. return 0;
  128. }
  129. }
  130. static void SetConcatChildren(CordRepConcat* concat, CordRep* left,
  131. CordRep* right) {
  132. concat->left = left;
  133. concat->right = right;
  134. concat->length = left->length + right->length;
  135. concat->set_depth(1 + std::max(Depth(left), Depth(right)));
  136. }
  137. // Create a concatenation of the specified nodes.
  138. // Does not change the refcounts of "left" and "right".
  139. // The returned node has a refcount of 1.
  140. static CordRep* RawConcat(CordRep* left, CordRep* right) {
  141. // Avoid making degenerate concat nodes (one child is empty)
  142. if (left == nullptr) return right;
  143. if (right == nullptr) return left;
  144. if (left->length == 0) {
  145. CordRep::Unref(left);
  146. return right;
  147. }
  148. if (right->length == 0) {
  149. CordRep::Unref(right);
  150. return left;
  151. }
  152. CordRepConcat* rep = new CordRepConcat();
  153. rep->tag = cord_internal::CONCAT;
  154. SetConcatChildren(rep, left, right);
  155. return rep;
  156. }
  157. static CordRep* Concat(CordRep* left, CordRep* right) {
  158. CordRep* rep = RawConcat(left, right);
  159. if (rep != nullptr && !IsRootBalanced(rep)) {
  160. rep = Rebalance(rep);
  161. }
  162. return VerifyTree(rep);
  163. }
  164. // Make a balanced tree out of an array of leaf nodes.
  165. static CordRep* MakeBalancedTree(CordRep** reps, size_t n) {
  166. // Make repeated passes over the array, merging adjacent pairs
  167. // until we are left with just a single node.
  168. while (n > 1) {
  169. size_t dst = 0;
  170. for (size_t src = 0; src < n; src += 2) {
  171. if (src + 1 < n) {
  172. reps[dst] = Concat(reps[src], reps[src + 1]);
  173. } else {
  174. reps[dst] = reps[src];
  175. }
  176. dst++;
  177. }
  178. n = dst;
  179. }
  180. return reps[0];
  181. }
  182. static CordRepFlat* CreateFlat(const char* data, size_t length,
  183. size_t alloc_hint) {
  184. CordRepFlat* flat = CordRepFlat::New(length + alloc_hint);
  185. flat->length = length;
  186. memcpy(flat->Data(), data, length);
  187. return flat;
  188. }
  189. // Creates a new flat or Btree out of the specified array.
  190. // The returned node has a refcount of 1.
  191. static CordRep* NewBtree(const char* data, size_t length, size_t alloc_hint) {
  192. if (length <= kMaxFlatLength) {
  193. return CreateFlat(data, length, alloc_hint);
  194. }
  195. CordRepFlat* flat = CreateFlat(data, kMaxFlatLength, 0);
  196. data += kMaxFlatLength;
  197. length -= kMaxFlatLength;
  198. auto* root = CordRepBtree::Create(flat);
  199. return CordRepBtree::Append(root, {data, length}, alloc_hint);
  200. }
  201. // Create a new tree out of the specified array.
  202. // The returned node has a refcount of 1.
  203. static CordRep* NewTree(const char* data, size_t length, size_t alloc_hint) {
  204. if (length == 0) return nullptr;
  205. if (btree_enabled()) {
  206. return NewBtree(data, length, alloc_hint);
  207. }
  208. absl::FixedArray<CordRep*> reps((length - 1) / kMaxFlatLength + 1);
  209. size_t n = 0;
  210. do {
  211. const size_t len = std::min(length, kMaxFlatLength);
  212. CordRepFlat* rep = CordRepFlat::New(len + alloc_hint);
  213. rep->length = len;
  214. memcpy(rep->Data(), data, len);
  215. reps[n++] = VerifyTree(rep);
  216. data += len;
  217. length -= len;
  218. } while (length != 0);
  219. return MakeBalancedTree(reps.data(), n);
  220. }
  221. namespace cord_internal {
  222. void InitializeCordRepExternal(absl::string_view data, CordRepExternal* rep) {
  223. assert(!data.empty());
  224. rep->length = data.size();
  225. rep->tag = EXTERNAL;
  226. rep->base = data.data();
  227. VerifyTree(rep);
  228. }
  229. } // namespace cord_internal
  230. static CordRep* NewSubstring(CordRep* child, size_t offset, size_t length) {
  231. // Never create empty substring nodes
  232. if (length == 0) {
  233. CordRep::Unref(child);
  234. return nullptr;
  235. } else {
  236. CordRepSubstring* rep = new CordRepSubstring();
  237. assert((offset + length) <= child->length);
  238. rep->length = length;
  239. rep->tag = cord_internal::SUBSTRING;
  240. rep->start = offset;
  241. rep->child = child;
  242. return VerifyTree(rep);
  243. }
  244. }
  245. // Creates a CordRep from the provided string. If the string is large enough,
  246. // and not wasteful, we move the string into an external cord rep, preserving
  247. // the already allocated string contents.
  248. // Requires the provided string length to be larger than `kMaxInline`.
  249. static CordRep* CordRepFromString(std::string&& src) {
  250. assert(src.length() > cord_internal::kMaxInline);
  251. if (
  252. // String is short: copy data to avoid external block overhead.
  253. src.size() <= kMaxBytesToCopy ||
  254. // String is wasteful: copy data to avoid pinning too much unused memory.
  255. src.size() < src.capacity() / 2
  256. ) {
  257. return NewTree(src.data(), src.size(), 0);
  258. }
  259. struct StringReleaser {
  260. void operator()(absl::string_view /* data */) {}
  261. std::string data;
  262. };
  263. const absl::string_view original_data = src;
  264. auto* rep =
  265. static_cast<::absl::cord_internal::CordRepExternalImpl<StringReleaser>*>(
  266. absl::cord_internal::NewExternalRep(original_data,
  267. StringReleaser{std::move(src)}));
  268. // Moving src may have invalidated its data pointer, so adjust it.
  269. rep->base = rep->template get<0>().data.data();
  270. return rep;
  271. }
  272. // --------------------------------------------------------------------
  273. // Cord::InlineRep functions
  274. constexpr unsigned char Cord::InlineRep::kMaxInline;
  275. inline void Cord::InlineRep::set_data(const char* data, size_t n,
  276. bool nullify_tail) {
  277. static_assert(kMaxInline == 15, "set_data is hard-coded for a length of 15");
  278. cord_internal::SmallMemmove(data_.as_chars(), data, n, nullify_tail);
  279. set_inline_size(n);
  280. }
  281. inline char* Cord::InlineRep::set_data(size_t n) {
  282. assert(n <= kMaxInline);
  283. ResetToEmpty();
  284. set_inline_size(n);
  285. return data_.as_chars();
  286. }
  287. inline void Cord::InlineRep::reduce_size(size_t n) {
  288. size_t tag = inline_size();
  289. assert(tag <= kMaxInline);
  290. assert(tag >= n);
  291. tag -= n;
  292. memset(data_.as_chars() + tag, 0, n);
  293. set_inline_size(static_cast<char>(tag));
  294. }
  295. inline void Cord::InlineRep::remove_prefix(size_t n) {
  296. cord_internal::SmallMemmove(data_.as_chars(), data_.as_chars() + n,
  297. inline_size() - n);
  298. reduce_size(n);
  299. }
  300. // Returns `rep` converted into a CordRepBtree.
  301. // Directly returns `rep` if `rep` is already a CordRepBtree.
  302. static CordRepBtree* ForceBtree(CordRep* rep) {
  303. return rep->IsBtree() ? rep->btree() : CordRepBtree::Create(rep);
  304. }
  305. void Cord::InlineRep::AppendTreeToInlined(CordRep* tree,
  306. MethodIdentifier method) {
  307. assert(!is_tree());
  308. if (!data_.is_empty()) {
  309. CordRepFlat* flat = MakeFlatWithExtraCapacity(0);
  310. if (btree_enabled()) {
  311. tree = CordRepBtree::Append(CordRepBtree::Create(flat), tree);
  312. } else {
  313. tree = Concat(flat, tree);
  314. }
  315. }
  316. EmplaceTree(tree, method);
  317. }
  318. void Cord::InlineRep::AppendTreeToTree(CordRep* tree, MethodIdentifier method) {
  319. assert(is_tree());
  320. const CordzUpdateScope scope(data_.cordz_info(), method);
  321. if (btree_enabled()) {
  322. tree = CordRepBtree::Append(ForceBtree(data_.as_tree()), tree);
  323. } else {
  324. tree = Concat(data_.as_tree(), tree);
  325. }
  326. SetTree(tree, scope);
  327. }
  328. void Cord::InlineRep::AppendTree(CordRep* tree, MethodIdentifier method) {
  329. if (tree == nullptr) return;
  330. if (data_.is_tree()) {
  331. AppendTreeToTree(tree, method);
  332. } else {
  333. AppendTreeToInlined(tree, method);
  334. }
  335. }
  336. void Cord::InlineRep::PrependTreeToInlined(CordRep* tree,
  337. MethodIdentifier method) {
  338. assert(!is_tree());
  339. if (!data_.is_empty()) {
  340. CordRepFlat* flat = MakeFlatWithExtraCapacity(0);
  341. if (btree_enabled()) {
  342. tree = CordRepBtree::Prepend(CordRepBtree::Create(flat), tree);
  343. } else {
  344. tree = Concat(tree, flat);
  345. }
  346. }
  347. EmplaceTree(tree, method);
  348. }
  349. void Cord::InlineRep::PrependTreeToTree(CordRep* tree,
  350. MethodIdentifier method) {
  351. assert(is_tree());
  352. const CordzUpdateScope scope(data_.cordz_info(), method);
  353. if (btree_enabled()) {
  354. tree = CordRepBtree::Prepend(ForceBtree(data_.as_tree()), tree);
  355. } else {
  356. tree = Concat(tree, data_.as_tree());
  357. }
  358. SetTree(tree, scope);
  359. }
  360. void Cord::InlineRep::PrependTree(CordRep* tree, MethodIdentifier method) {
  361. assert(tree != nullptr);
  362. if (data_.is_tree()) {
  363. PrependTreeToTree(tree, method);
  364. } else {
  365. PrependTreeToInlined(tree, method);
  366. }
  367. }
  368. // Searches for a non-full flat node at the rightmost leaf of the tree. If a
  369. // suitable leaf is found, the function will update the length field for all
  370. // nodes to account for the size increase. The append region address will be
  371. // written to region and the actual size increase will be written to size.
  372. static inline bool PrepareAppendRegion(CordRep* root, char** region,
  373. size_t* size, size_t max_length) {
  374. if (root->IsBtree() && root->refcount.IsMutable()) {
  375. Span<char> span = root->btree()->GetAppendBuffer(max_length);
  376. if (!span.empty()) {
  377. *region = span.data();
  378. *size = span.size();
  379. return true;
  380. }
  381. }
  382. // Search down the right-hand path for a non-full FLAT node.
  383. CordRep* dst = root;
  384. while (dst->IsConcat() && dst->refcount.IsMutable()) {
  385. dst = dst->concat()->right;
  386. }
  387. if (!dst->IsFlat() || !dst->refcount.IsMutable()) {
  388. *region = nullptr;
  389. *size = 0;
  390. return false;
  391. }
  392. const size_t in_use = dst->length;
  393. const size_t capacity = dst->flat()->Capacity();
  394. if (in_use == capacity) {
  395. *region = nullptr;
  396. *size = 0;
  397. return false;
  398. }
  399. size_t size_increase = std::min(capacity - in_use, max_length);
  400. // We need to update the length fields for all nodes, including the leaf node.
  401. for (CordRep* rep = root; rep != dst; rep = rep->concat()->right) {
  402. rep->length += size_increase;
  403. }
  404. dst->length += size_increase;
  405. *region = dst->flat()->Data() + in_use;
  406. *size = size_increase;
  407. return true;
  408. }
  409. template <bool has_length>
  410. void Cord::InlineRep::GetAppendRegion(char** region, size_t* size,
  411. size_t length) {
  412. auto constexpr method = CordzUpdateTracker::kGetAppendRegion;
  413. CordRep* root = tree();
  414. size_t sz = root ? root->length : inline_size();
  415. if (root == nullptr) {
  416. size_t available = kMaxInline - sz;
  417. if (available >= (has_length ? length : 1)) {
  418. *region = data_.as_chars() + sz;
  419. *size = has_length ? length : available;
  420. set_inline_size(has_length ? sz + length : kMaxInline);
  421. return;
  422. }
  423. }
  424. size_t extra = has_length ? length : (std::max)(sz, kMinFlatLength);
  425. CordRep* rep = root ? root : MakeFlatWithExtraCapacity(extra);
  426. CordzUpdateScope scope(root ? data_.cordz_info() : nullptr, method);
  427. if (PrepareAppendRegion(rep, region, size, length)) {
  428. CommitTree(root, rep, scope, method);
  429. return;
  430. }
  431. // Allocate new node.
  432. CordRepFlat* new_node = CordRepFlat::New(extra);
  433. new_node->length = std::min(new_node->Capacity(), length);
  434. *region = new_node->Data();
  435. *size = new_node->length;
  436. if (btree_enabled()) {
  437. rep = CordRepBtree::Append(ForceBtree(rep), new_node);
  438. } else {
  439. rep = Concat(rep, new_node);
  440. }
  441. CommitTree(root, rep, scope, method);
  442. }
  443. // Computes the memory side of the provided edge which must be a valid data edge
  444. // for a btrtee, i.e., a FLAT, EXTERNAL or SUBSTRING of a FLAT or EXTERNAL node.
  445. static bool RepMemoryUsageDataEdge(const CordRep* rep,
  446. size_t* total_mem_usage) {
  447. size_t maybe_sub_size = 0;
  448. if (ABSL_PREDICT_FALSE(rep->IsSubstring())) {
  449. maybe_sub_size = sizeof(cord_internal::CordRepSubstring);
  450. rep = rep->substring()->child;
  451. }
  452. if (rep->IsFlat()) {
  453. *total_mem_usage += maybe_sub_size + rep->flat()->AllocatedSize();
  454. return true;
  455. }
  456. if (rep->IsExternal()) {
  457. // We don't know anything about the embedded / bound data, but we can safely
  458. // assume it is 'at least' a word / pointer to data. In the future we may
  459. // choose to use the 'data' byte as a tag to identify the types of some
  460. // well-known externals, such as a std::string instance.
  461. *total_mem_usage += maybe_sub_size +
  462. sizeof(cord_internal::CordRepExternalImpl<intptr_t>) +
  463. rep->length;
  464. return true;
  465. }
  466. return false;
  467. }
  468. // If the rep is a leaf, this will increment the value at total_mem_usage and
  469. // will return true.
  470. static bool RepMemoryUsageLeaf(const CordRep* rep, size_t* total_mem_usage) {
  471. if (rep->IsFlat()) {
  472. *total_mem_usage += rep->flat()->AllocatedSize();
  473. return true;
  474. }
  475. if (rep->IsExternal()) {
  476. // We don't know anything about the embedded / bound data, but we can safely
  477. // assume it is 'at least' a word / pointer to data. In the future we may
  478. // choose to use the 'data' byte as a tag to identify the types of some
  479. // well-known externals, such as a std::string instance.
  480. *total_mem_usage +=
  481. sizeof(cord_internal::CordRepExternalImpl<intptr_t>) + rep->length;
  482. return true;
  483. }
  484. return false;
  485. }
  486. void Cord::InlineRep::AssignSlow(const Cord::InlineRep& src) {
  487. assert(&src != this);
  488. assert(is_tree() || src.is_tree());
  489. auto constexpr method = CordzUpdateTracker::kAssignCord;
  490. if (ABSL_PREDICT_TRUE(!is_tree())) {
  491. EmplaceTree(CordRep::Ref(src.as_tree()), src.data_, method);
  492. return;
  493. }
  494. CordRep* tree = as_tree();
  495. if (CordRep* src_tree = src.tree()) {
  496. // Leave any existing `cordz_info` in place, and let MaybeTrackCord()
  497. // decide if this cord should be (or remains to be) sampled or not.
  498. data_.set_tree(CordRep::Ref(src_tree));
  499. CordzInfo::MaybeTrackCord(data_, src.data_, method);
  500. } else {
  501. CordzInfo::MaybeUntrackCord(data_.cordz_info());
  502. data_ = src.data_;
  503. }
  504. CordRep::Unref(tree);
  505. }
  506. void Cord::InlineRep::UnrefTree() {
  507. if (is_tree()) {
  508. CordzInfo::MaybeUntrackCord(data_.cordz_info());
  509. CordRep::Unref(tree());
  510. }
  511. }
  512. // --------------------------------------------------------------------
  513. // Constructors and destructors
  514. Cord::Cord(absl::string_view src, MethodIdentifier method)
  515. : contents_(InlineData::kDefaultInit) {
  516. const size_t n = src.size();
  517. if (n <= InlineRep::kMaxInline) {
  518. contents_.set_data(src.data(), n, true);
  519. } else {
  520. CordRep* rep = NewTree(src.data(), n, 0);
  521. contents_.EmplaceTree(rep, method);
  522. }
  523. }
  524. template <typename T, Cord::EnableIfString<T>>
  525. Cord::Cord(T&& src) : contents_(InlineData::kDefaultInit) {
  526. if (src.size() <= InlineRep::kMaxInline) {
  527. contents_.set_data(src.data(), src.size(), true);
  528. } else {
  529. CordRep* rep = CordRepFromString(std::forward<T>(src));
  530. contents_.EmplaceTree(rep, CordzUpdateTracker::kConstructorString);
  531. }
  532. }
  533. template Cord::Cord(std::string&& src);
  534. // The destruction code is separate so that the compiler can determine
  535. // that it does not need to call the destructor on a moved-from Cord.
  536. void Cord::DestroyCordSlow() {
  537. assert(contents_.is_tree());
  538. CordzInfo::MaybeUntrackCord(contents_.cordz_info());
  539. CordRep::Unref(VerifyTree(contents_.as_tree()));
  540. }
  541. // --------------------------------------------------------------------
  542. // Mutators
  543. void Cord::Clear() {
  544. if (CordRep* tree = contents_.clear()) {
  545. CordRep::Unref(tree);
  546. }
  547. }
  548. Cord& Cord::AssignLargeString(std::string&& src) {
  549. auto constexpr method = CordzUpdateTracker::kAssignString;
  550. assert(src.size() > kMaxBytesToCopy);
  551. CordRep* rep = CordRepFromString(std::move(src));
  552. if (CordRep* tree = contents_.tree()) {
  553. CordzUpdateScope scope(contents_.cordz_info(), method);
  554. contents_.SetTree(rep, scope);
  555. CordRep::Unref(tree);
  556. } else {
  557. contents_.EmplaceTree(rep, method);
  558. }
  559. return *this;
  560. }
  561. Cord& Cord::operator=(absl::string_view src) {
  562. auto constexpr method = CordzUpdateTracker::kAssignString;
  563. const char* data = src.data();
  564. size_t length = src.size();
  565. CordRep* tree = contents_.tree();
  566. if (length <= InlineRep::kMaxInline) {
  567. // Embed into this->contents_, which is somewhat subtle:
  568. // - MaybeUntrackCord must be called before Unref(tree).
  569. // - MaybeUntrackCord must be called before set_data() clobbers cordz_info.
  570. // - set_data() must be called before Unref(tree) as it may reference tree.
  571. if (tree != nullptr) CordzInfo::MaybeUntrackCord(contents_.cordz_info());
  572. contents_.set_data(data, length, true);
  573. if (tree != nullptr) CordRep::Unref(tree);
  574. return *this;
  575. }
  576. if (tree != nullptr) {
  577. CordzUpdateScope scope(contents_.cordz_info(), method);
  578. if (tree->IsFlat() && tree->flat()->Capacity() >= length &&
  579. tree->refcount.IsMutable()) {
  580. // Copy in place if the existing FLAT node is reusable.
  581. memmove(tree->flat()->Data(), data, length);
  582. tree->length = length;
  583. VerifyTree(tree);
  584. return *this;
  585. }
  586. contents_.SetTree(NewTree(data, length, 0), scope);
  587. CordRep::Unref(tree);
  588. } else {
  589. contents_.EmplaceTree(NewTree(data, length, 0), method);
  590. }
  591. return *this;
  592. }
  593. // TODO(sanjay): Move to Cord::InlineRep section of file. For now,
  594. // we keep it here to make diffs easier.
  595. void Cord::InlineRep::AppendArray(absl::string_view src,
  596. MethodIdentifier method) {
  597. if (src.empty()) return; // memcpy(_, nullptr, 0) is undefined.
  598. size_t appended = 0;
  599. CordRep* rep = tree();
  600. const CordRep* const root = rep;
  601. CordzUpdateScope scope(root ? cordz_info() : nullptr, method);
  602. if (root != nullptr) {
  603. char* region;
  604. if (PrepareAppendRegion(rep, &region, &appended, src.size())) {
  605. memcpy(region, src.data(), appended);
  606. }
  607. } else {
  608. // Try to fit in the inline buffer if possible.
  609. size_t inline_length = inline_size();
  610. if (src.size() <= kMaxInline - inline_length) {
  611. // Append new data to embedded array
  612. memcpy(data_.as_chars() + inline_length, src.data(), src.size());
  613. set_inline_size(inline_length + src.size());
  614. return;
  615. }
  616. // Allocate flat to be a perfect fit on first append exceeding inlined size.
  617. // Subsequent growth will use amortized growth until we reach maximum flat
  618. // size.
  619. rep = CordRepFlat::New(inline_length + src.size());
  620. appended = std::min(src.size(), rep->flat()->Capacity() - inline_length);
  621. memcpy(rep->flat()->Data(), data_.as_chars(), inline_length);
  622. memcpy(rep->flat()->Data() + inline_length, src.data(), appended);
  623. rep->length = inline_length + appended;
  624. }
  625. src.remove_prefix(appended);
  626. if (src.empty()) {
  627. CommitTree(root, rep, scope, method);
  628. return;
  629. }
  630. if (btree_enabled()) {
  631. // TODO(b/192061034): keep legacy 10% growth rate: consider other rates.
  632. rep = ForceBtree(rep);
  633. const size_t min_growth = std::max<size_t>(rep->length / 10, src.size());
  634. rep = CordRepBtree::Append(rep->btree(), src, min_growth - src.size());
  635. } else {
  636. // Use new block(s) for any remaining bytes that were not handled above.
  637. // Alloc extra memory only if the right child of the root of the new tree
  638. // is going to be a FLAT node, which will permit further inplace appends.
  639. size_t length = src.size();
  640. if (src.size() < kMaxFlatLength) {
  641. // The new length is either
  642. // - old size + 10%
  643. // - old_size + src.size()
  644. // This will cause a reasonable conservative step-up in size that is
  645. // still large enough to avoid excessive amounts of small fragments
  646. // being added.
  647. length = std::max<size_t>(rep->length / 10, src.size());
  648. }
  649. rep = Concat(rep, NewTree(src.data(), src.size(), length - src.size()));
  650. }
  651. CommitTree(root, rep, scope, method);
  652. }
  653. inline CordRep* Cord::TakeRep() const& {
  654. return CordRep::Ref(contents_.tree());
  655. }
  656. inline CordRep* Cord::TakeRep() && {
  657. CordRep* rep = contents_.tree();
  658. contents_.clear();
  659. return rep;
  660. }
  661. template <typename C>
  662. inline void Cord::AppendImpl(C&& src) {
  663. auto constexpr method = CordzUpdateTracker::kAppendCord;
  664. if (empty()) {
  665. // Since destination is empty, we can avoid allocating a node,
  666. if (src.contents_.is_tree()) {
  667. // by taking the tree directly
  668. CordRep* rep = std::forward<C>(src).TakeRep();
  669. contents_.EmplaceTree(rep, method);
  670. } else {
  671. // or copying over inline data
  672. contents_.data_ = src.contents_.data_;
  673. }
  674. return;
  675. }
  676. // For short cords, it is faster to copy data if there is room in dst.
  677. const size_t src_size = src.contents_.size();
  678. if (src_size <= kMaxBytesToCopy) {
  679. CordRep* src_tree = src.contents_.tree();
  680. if (src_tree == nullptr) {
  681. // src has embedded data.
  682. contents_.AppendArray({src.contents_.data(), src_size}, method);
  683. return;
  684. }
  685. if (src_tree->IsFlat()) {
  686. // src tree just has one flat node.
  687. contents_.AppendArray({src_tree->flat()->Data(), src_size}, method);
  688. return;
  689. }
  690. if (&src == this) {
  691. // ChunkIterator below assumes that src is not modified during traversal.
  692. Append(Cord(src));
  693. return;
  694. }
  695. // TODO(mec): Should we only do this if "dst" has space?
  696. for (absl::string_view chunk : src.Chunks()) {
  697. Append(chunk);
  698. }
  699. return;
  700. }
  701. // Guaranteed to be a tree (kMaxBytesToCopy > kInlinedSize)
  702. CordRep* rep = std::forward<C>(src).TakeRep();
  703. contents_.AppendTree(rep, CordzUpdateTracker::kAppendCord);
  704. }
  705. void Cord::Append(const Cord& src) {
  706. AppendImpl(src);
  707. }
  708. void Cord::Append(Cord&& src) {
  709. AppendImpl(std::move(src));
  710. }
  711. template <typename T, Cord::EnableIfString<T>>
  712. void Cord::Append(T&& src) {
  713. if (src.size() <= kMaxBytesToCopy) {
  714. Append(absl::string_view(src));
  715. } else {
  716. CordRep* rep = CordRepFromString(std::forward<T>(src));
  717. contents_.AppendTree(rep, CordzUpdateTracker::kAppendString);
  718. }
  719. }
  720. template void Cord::Append(std::string&& src);
  721. void Cord::Prepend(const Cord& src) {
  722. CordRep* src_tree = src.contents_.tree();
  723. if (src_tree != nullptr) {
  724. CordRep::Ref(src_tree);
  725. contents_.PrependTree(src_tree, CordzUpdateTracker::kPrependCord);
  726. return;
  727. }
  728. // `src` cord is inlined.
  729. absl::string_view src_contents(src.contents_.data(), src.contents_.size());
  730. return Prepend(src_contents);
  731. }
  732. void Cord::PrependArray(absl::string_view src, MethodIdentifier method) {
  733. if (src.empty()) return; // memcpy(_, nullptr, 0) is undefined.
  734. if (!contents_.is_tree()) {
  735. size_t cur_size = contents_.inline_size();
  736. if (cur_size + src.size() <= InlineRep::kMaxInline) {
  737. // Use embedded storage.
  738. char data[InlineRep::kMaxInline + 1] = {0};
  739. memcpy(data, src.data(), src.size());
  740. memcpy(data + src.size(), contents_.data(), cur_size);
  741. memcpy(contents_.data_.as_chars(), data, InlineRep::kMaxInline + 1);
  742. contents_.set_inline_size(cur_size + src.size());
  743. return;
  744. }
  745. }
  746. CordRep* rep = NewTree(src.data(), src.size(), 0);
  747. contents_.PrependTree(rep, method);
  748. }
  749. template <typename T, Cord::EnableIfString<T>>
  750. inline void Cord::Prepend(T&& src) {
  751. if (src.size() <= kMaxBytesToCopy) {
  752. Prepend(absl::string_view(src));
  753. } else {
  754. CordRep* rep = CordRepFromString(std::forward<T>(src));
  755. contents_.PrependTree(rep, CordzUpdateTracker::kPrependString);
  756. }
  757. }
  758. template void Cord::Prepend(std::string&& src);
  759. static CordRep* RemovePrefixFrom(CordRep* node, size_t n) {
  760. if (n >= node->length) return nullptr;
  761. if (n == 0) return CordRep::Ref(node);
  762. absl::InlinedVector<CordRep*, kInlinedVectorSize> rhs_stack;
  763. while (node->IsConcat()) {
  764. assert(n <= node->length);
  765. if (n < node->concat()->left->length) {
  766. // Push right to stack, descend left.
  767. rhs_stack.push_back(node->concat()->right);
  768. node = node->concat()->left;
  769. } else {
  770. // Drop left, descend right.
  771. n -= node->concat()->left->length;
  772. node = node->concat()->right;
  773. }
  774. }
  775. assert(n <= node->length);
  776. if (n == 0) {
  777. CordRep::Ref(node);
  778. } else {
  779. size_t start = n;
  780. size_t len = node->length - n;
  781. if (node->IsSubstring()) {
  782. // Consider in-place update of node, similar to in RemoveSuffixFrom().
  783. start += node->substring()->start;
  784. node = node->substring()->child;
  785. }
  786. node = NewSubstring(CordRep::Ref(node), start, len);
  787. }
  788. while (!rhs_stack.empty()) {
  789. node = Concat(node, CordRep::Ref(rhs_stack.back()));
  790. rhs_stack.pop_back();
  791. }
  792. return node;
  793. }
  794. // RemoveSuffixFrom() is very similar to RemovePrefixFrom(), with the
  795. // exception that removing a suffix has an optimization where a node may be
  796. // edited in place iff that node and all its ancestors have a refcount of 1.
  797. static CordRep* RemoveSuffixFrom(CordRep* node, size_t n) {
  798. if (n >= node->length) return nullptr;
  799. if (n == 0) return CordRep::Ref(node);
  800. absl::InlinedVector<CordRep*, kInlinedVectorSize> lhs_stack;
  801. bool inplace_ok = node->refcount.IsMutable();
  802. while (node->IsConcat()) {
  803. assert(n <= node->length);
  804. if (n < node->concat()->right->length) {
  805. // Push left to stack, descend right.
  806. lhs_stack.push_back(node->concat()->left);
  807. node = node->concat()->right;
  808. } else {
  809. // Drop right, descend left.
  810. n -= node->concat()->right->length;
  811. node = node->concat()->left;
  812. }
  813. inplace_ok = inplace_ok && node->refcount.IsMutable();
  814. }
  815. assert(n <= node->length);
  816. if (n == 0) {
  817. CordRep::Ref(node);
  818. } else if (inplace_ok && !node->IsExternal()) {
  819. // Consider making a new buffer if the current node capacity is much
  820. // larger than the new length.
  821. CordRep::Ref(node);
  822. node->length -= n;
  823. } else {
  824. size_t start = 0;
  825. size_t len = node->length - n;
  826. if (node->IsSubstring()) {
  827. start = node->substring()->start;
  828. node = node->substring()->child;
  829. }
  830. node = NewSubstring(CordRep::Ref(node), start, len);
  831. }
  832. while (!lhs_stack.empty()) {
  833. node = Concat(CordRep::Ref(lhs_stack.back()), node);
  834. lhs_stack.pop_back();
  835. }
  836. return node;
  837. }
  838. void Cord::RemovePrefix(size_t n) {
  839. ABSL_INTERNAL_CHECK(n <= size(),
  840. absl::StrCat("Requested prefix size ", n,
  841. " exceeds Cord's size ", size()));
  842. CordRep* tree = contents_.tree();
  843. if (tree == nullptr) {
  844. contents_.remove_prefix(n);
  845. } else {
  846. auto constexpr method = CordzUpdateTracker::kRemovePrefix;
  847. CordzUpdateScope scope(contents_.cordz_info(), method);
  848. if (tree->IsBtree()) {
  849. CordRep* old = tree;
  850. tree = tree->btree()->SubTree(n, tree->length - n);
  851. CordRep::Unref(old);
  852. } else {
  853. CordRep* newrep = RemovePrefixFrom(tree, n);
  854. CordRep::Unref(tree);
  855. tree = VerifyTree(newrep);
  856. }
  857. contents_.SetTreeOrEmpty(tree, scope);
  858. }
  859. }
  860. void Cord::RemoveSuffix(size_t n) {
  861. ABSL_INTERNAL_CHECK(n <= size(),
  862. absl::StrCat("Requested suffix size ", n,
  863. " exceeds Cord's size ", size()));
  864. CordRep* tree = contents_.tree();
  865. if (tree == nullptr) {
  866. contents_.reduce_size(n);
  867. } else {
  868. auto constexpr method = CordzUpdateTracker::kRemoveSuffix;
  869. CordzUpdateScope scope(contents_.cordz_info(), method);
  870. if (tree->IsBtree()) {
  871. tree = CordRepBtree::RemoveSuffix(tree->btree(), n);
  872. } else {
  873. CordRep* newrep = RemoveSuffixFrom(tree, n);
  874. CordRep::Unref(tree);
  875. tree = VerifyTree(newrep);
  876. }
  877. contents_.SetTreeOrEmpty(tree, scope);
  878. }
  879. }
  880. // Work item for NewSubRange().
  881. struct SubRange {
  882. SubRange(CordRep* a_node, size_t a_pos, size_t a_n)
  883. : node(a_node), pos(a_pos), n(a_n) {}
  884. CordRep* node; // nullptr means concat last 2 results.
  885. size_t pos;
  886. size_t n;
  887. };
  888. static CordRep* NewSubRange(CordRep* node, size_t pos, size_t n) {
  889. absl::InlinedVector<CordRep*, kInlinedVectorSize> results;
  890. absl::InlinedVector<SubRange, kInlinedVectorSize> todo;
  891. todo.push_back(SubRange(node, pos, n));
  892. do {
  893. const SubRange& sr = todo.back();
  894. node = sr.node;
  895. pos = sr.pos;
  896. n = sr.n;
  897. todo.pop_back();
  898. if (node == nullptr) {
  899. assert(results.size() >= 2);
  900. CordRep* right = results.back();
  901. results.pop_back();
  902. CordRep* left = results.back();
  903. results.pop_back();
  904. results.push_back(Concat(left, right));
  905. } else if (pos == 0 && n == node->length) {
  906. results.push_back(CordRep::Ref(node));
  907. } else if (!node->IsConcat()) {
  908. if (node->IsSubstring()) {
  909. pos += node->substring()->start;
  910. node = node->substring()->child;
  911. }
  912. results.push_back(NewSubstring(CordRep::Ref(node), pos, n));
  913. } else if (pos + n <= node->concat()->left->length) {
  914. todo.push_back(SubRange(node->concat()->left, pos, n));
  915. } else if (pos >= node->concat()->left->length) {
  916. pos -= node->concat()->left->length;
  917. todo.push_back(SubRange(node->concat()->right, pos, n));
  918. } else {
  919. size_t left_n = node->concat()->left->length - pos;
  920. todo.push_back(SubRange(nullptr, 0, 0)); // Concat()
  921. todo.push_back(SubRange(node->concat()->right, 0, n - left_n));
  922. todo.push_back(SubRange(node->concat()->left, pos, left_n));
  923. }
  924. } while (!todo.empty());
  925. assert(results.size() == 1);
  926. return results[0];
  927. }
  928. Cord Cord::Subcord(size_t pos, size_t new_size) const {
  929. Cord sub_cord;
  930. size_t length = size();
  931. if (pos > length) pos = length;
  932. if (new_size > length - pos) new_size = length - pos;
  933. if (new_size == 0) return sub_cord;
  934. CordRep* tree = contents_.tree();
  935. if (tree == nullptr) {
  936. // sub_cord is newly constructed, no need to re-zero-out the tail of
  937. // contents_ memory.
  938. sub_cord.contents_.set_data(contents_.data() + pos, new_size, false);
  939. return sub_cord;
  940. }
  941. if (new_size <= InlineRep::kMaxInline) {
  942. char* dest = sub_cord.contents_.data_.as_chars();
  943. Cord::ChunkIterator it = chunk_begin();
  944. it.AdvanceBytes(pos);
  945. size_t remaining_size = new_size;
  946. while (remaining_size > it->size()) {
  947. cord_internal::SmallMemmove(dest, it->data(), it->size());
  948. remaining_size -= it->size();
  949. dest += it->size();
  950. ++it;
  951. }
  952. cord_internal::SmallMemmove(dest, it->data(), remaining_size);
  953. sub_cord.contents_.set_inline_size(new_size);
  954. return sub_cord;
  955. }
  956. if (tree->IsBtree()) {
  957. tree = tree->btree()->SubTree(pos, new_size);
  958. } else {
  959. tree = NewSubRange(tree, pos, new_size);
  960. }
  961. sub_cord.contents_.EmplaceTree(tree, contents_.data_,
  962. CordzUpdateTracker::kSubCord);
  963. return sub_cord;
  964. }
  965. // --------------------------------------------------------------------
  966. // Balancing
  967. class CordForest {
  968. public:
  969. explicit CordForest(size_t length)
  970. : root_length_(length), trees_(kMinLengthSize, nullptr) {}
  971. void Build(CordRep* cord_root) {
  972. std::vector<CordRep*> pending = {cord_root};
  973. while (!pending.empty()) {
  974. CordRep* node = pending.back();
  975. pending.pop_back();
  976. CheckNode(node);
  977. if (ABSL_PREDICT_FALSE(!node->IsConcat())) {
  978. AddNode(node);
  979. continue;
  980. }
  981. CordRepConcat* concat_node = node->concat();
  982. if (concat_node->depth() >= kMinLengthSize ||
  983. concat_node->length < min_length[concat_node->depth()]) {
  984. pending.push_back(concat_node->right);
  985. pending.push_back(concat_node->left);
  986. if (concat_node->refcount.IsOne()) {
  987. concat_node->left = concat_freelist_;
  988. concat_freelist_ = concat_node;
  989. } else {
  990. CordRep::Ref(concat_node->right);
  991. CordRep::Ref(concat_node->left);
  992. CordRep::Unref(concat_node);
  993. }
  994. } else {
  995. AddNode(node);
  996. }
  997. }
  998. }
  999. CordRep* ConcatNodes() {
  1000. CordRep* sum = nullptr;
  1001. for (auto* node : trees_) {
  1002. if (node == nullptr) continue;
  1003. sum = PrependNode(node, sum);
  1004. root_length_ -= node->length;
  1005. if (root_length_ == 0) break;
  1006. }
  1007. ABSL_INTERNAL_CHECK(sum != nullptr, "Failed to locate sum node");
  1008. return VerifyTree(sum);
  1009. }
  1010. private:
  1011. CordRep* AppendNode(CordRep* node, CordRep* sum) {
  1012. return (sum == nullptr) ? node : MakeConcat(sum, node);
  1013. }
  1014. CordRep* PrependNode(CordRep* node, CordRep* sum) {
  1015. return (sum == nullptr) ? node : MakeConcat(node, sum);
  1016. }
  1017. void AddNode(CordRep* node) {
  1018. CordRep* sum = nullptr;
  1019. // Collect together everything with which we will merge with node
  1020. int i = 0;
  1021. for (; node->length > min_length[i + 1]; ++i) {
  1022. auto& tree_at_i = trees_[i];
  1023. if (tree_at_i == nullptr) continue;
  1024. sum = PrependNode(tree_at_i, sum);
  1025. tree_at_i = nullptr;
  1026. }
  1027. sum = AppendNode(node, sum);
  1028. // Insert sum into appropriate place in the forest
  1029. for (; sum->length >= min_length[i]; ++i) {
  1030. auto& tree_at_i = trees_[i];
  1031. if (tree_at_i == nullptr) continue;
  1032. sum = MakeConcat(tree_at_i, sum);
  1033. tree_at_i = nullptr;
  1034. }
  1035. // min_length[0] == 1, which means sum->length >= min_length[0]
  1036. assert(i > 0);
  1037. trees_[i - 1] = sum;
  1038. }
  1039. // Make concat node trying to resue existing CordRepConcat nodes we
  1040. // already collected in the concat_freelist_.
  1041. CordRep* MakeConcat(CordRep* left, CordRep* right) {
  1042. if (concat_freelist_ == nullptr) return RawConcat(left, right);
  1043. CordRepConcat* rep = concat_freelist_;
  1044. if (concat_freelist_->left == nullptr) {
  1045. concat_freelist_ = nullptr;
  1046. } else {
  1047. concat_freelist_ = concat_freelist_->left->concat();
  1048. }
  1049. SetConcatChildren(rep, left, right);
  1050. return rep;
  1051. }
  1052. static void CheckNode(CordRep* node) {
  1053. ABSL_INTERNAL_CHECK(node->length != 0u, "");
  1054. if (node->IsConcat()) {
  1055. ABSL_INTERNAL_CHECK(node->concat()->left != nullptr, "");
  1056. ABSL_INTERNAL_CHECK(node->concat()->right != nullptr, "");
  1057. ABSL_INTERNAL_CHECK(node->length == (node->concat()->left->length +
  1058. node->concat()->right->length),
  1059. "");
  1060. }
  1061. }
  1062. size_t root_length_;
  1063. // use an inlined vector instead of a flat array to get bounds checking
  1064. absl::InlinedVector<CordRep*, kInlinedVectorSize> trees_;
  1065. // List of concat nodes we can re-use for Cord balancing.
  1066. CordRepConcat* concat_freelist_ = nullptr;
  1067. };
  1068. static CordRep* Rebalance(CordRep* node) {
  1069. VerifyTree(node);
  1070. assert(node->IsConcat());
  1071. if (node->length == 0) {
  1072. return nullptr;
  1073. }
  1074. CordForest forest(node->length);
  1075. forest.Build(node);
  1076. return forest.ConcatNodes();
  1077. }
  1078. // --------------------------------------------------------------------
  1079. // Comparators
  1080. namespace {
  1081. int ClampResult(int memcmp_res) {
  1082. return static_cast<int>(memcmp_res > 0) - static_cast<int>(memcmp_res < 0);
  1083. }
  1084. int CompareChunks(absl::string_view* lhs, absl::string_view* rhs,
  1085. size_t* size_to_compare) {
  1086. size_t compared_size = std::min(lhs->size(), rhs->size());
  1087. assert(*size_to_compare >= compared_size);
  1088. *size_to_compare -= compared_size;
  1089. int memcmp_res = ::memcmp(lhs->data(), rhs->data(), compared_size);
  1090. if (memcmp_res != 0) return memcmp_res;
  1091. lhs->remove_prefix(compared_size);
  1092. rhs->remove_prefix(compared_size);
  1093. return 0;
  1094. }
  1095. // This overload set computes comparison results from memcmp result. This
  1096. // interface is used inside GenericCompare below. Differet implementations
  1097. // are specialized for int and bool. For int we clamp result to {-1, 0, 1}
  1098. // set. For bool we just interested in "value == 0".
  1099. template <typename ResultType>
  1100. ResultType ComputeCompareResult(int memcmp_res) {
  1101. return ClampResult(memcmp_res);
  1102. }
  1103. template <>
  1104. bool ComputeCompareResult<bool>(int memcmp_res) {
  1105. return memcmp_res == 0;
  1106. }
  1107. } // namespace
  1108. // Helper routine. Locates the first flat or external chunk of the Cord without
  1109. // initializing the iterator, and returns a string_view referencing the data.
  1110. inline absl::string_view Cord::InlineRep::FindFlatStartPiece() const {
  1111. if (!is_tree()) {
  1112. return absl::string_view(data_.as_chars(), data_.inline_size());
  1113. }
  1114. CordRep* node = tree();
  1115. if (node->IsFlat()) {
  1116. return absl::string_view(node->flat()->Data(), node->length);
  1117. }
  1118. if (node->IsExternal()) {
  1119. return absl::string_view(node->external()->base, node->length);
  1120. }
  1121. if (node->IsBtree()) {
  1122. CordRepBtree* tree = node->btree();
  1123. int height = tree->height();
  1124. while (--height >= 0) {
  1125. tree = tree->Edge(CordRepBtree::kFront)->btree();
  1126. }
  1127. return tree->Data(tree->begin());
  1128. }
  1129. // Walk down the left branches until we hit a non-CONCAT node.
  1130. while (node->IsConcat()) {
  1131. node = node->concat()->left;
  1132. }
  1133. // Get the child node if we encounter a SUBSTRING.
  1134. size_t offset = 0;
  1135. size_t length = node->length;
  1136. assert(length != 0);
  1137. if (node->IsSubstring()) {
  1138. offset = node->substring()->start;
  1139. node = node->substring()->child;
  1140. }
  1141. if (node->IsFlat()) {
  1142. return absl::string_view(node->flat()->Data() + offset, length);
  1143. }
  1144. assert(node->IsExternal() && "Expect FLAT or EXTERNAL node here");
  1145. return absl::string_view(node->external()->base + offset, length);
  1146. }
  1147. inline int Cord::CompareSlowPath(absl::string_view rhs, size_t compared_size,
  1148. size_t size_to_compare) const {
  1149. auto advance = [](Cord::ChunkIterator* it, absl::string_view* chunk) {
  1150. if (!chunk->empty()) return true;
  1151. ++*it;
  1152. if (it->bytes_remaining_ == 0) return false;
  1153. *chunk = **it;
  1154. return true;
  1155. };
  1156. Cord::ChunkIterator lhs_it = chunk_begin();
  1157. // compared_size is inside first chunk.
  1158. absl::string_view lhs_chunk =
  1159. (lhs_it.bytes_remaining_ != 0) ? *lhs_it : absl::string_view();
  1160. assert(compared_size <= lhs_chunk.size());
  1161. assert(compared_size <= rhs.size());
  1162. lhs_chunk.remove_prefix(compared_size);
  1163. rhs.remove_prefix(compared_size);
  1164. size_to_compare -= compared_size; // skip already compared size.
  1165. while (advance(&lhs_it, &lhs_chunk) && !rhs.empty()) {
  1166. int comparison_result = CompareChunks(&lhs_chunk, &rhs, &size_to_compare);
  1167. if (comparison_result != 0) return comparison_result;
  1168. if (size_to_compare == 0) return 0;
  1169. }
  1170. return static_cast<int>(rhs.empty()) - static_cast<int>(lhs_chunk.empty());
  1171. }
  1172. inline int Cord::CompareSlowPath(const Cord& rhs, size_t compared_size,
  1173. size_t size_to_compare) const {
  1174. auto advance = [](Cord::ChunkIterator* it, absl::string_view* chunk) {
  1175. if (!chunk->empty()) return true;
  1176. ++*it;
  1177. if (it->bytes_remaining_ == 0) return false;
  1178. *chunk = **it;
  1179. return true;
  1180. };
  1181. Cord::ChunkIterator lhs_it = chunk_begin();
  1182. Cord::ChunkIterator rhs_it = rhs.chunk_begin();
  1183. // compared_size is inside both first chunks.
  1184. absl::string_view lhs_chunk =
  1185. (lhs_it.bytes_remaining_ != 0) ? *lhs_it : absl::string_view();
  1186. absl::string_view rhs_chunk =
  1187. (rhs_it.bytes_remaining_ != 0) ? *rhs_it : absl::string_view();
  1188. assert(compared_size <= lhs_chunk.size());
  1189. assert(compared_size <= rhs_chunk.size());
  1190. lhs_chunk.remove_prefix(compared_size);
  1191. rhs_chunk.remove_prefix(compared_size);
  1192. size_to_compare -= compared_size; // skip already compared size.
  1193. while (advance(&lhs_it, &lhs_chunk) && advance(&rhs_it, &rhs_chunk)) {
  1194. int memcmp_res = CompareChunks(&lhs_chunk, &rhs_chunk, &size_to_compare);
  1195. if (memcmp_res != 0) return memcmp_res;
  1196. if (size_to_compare == 0) return 0;
  1197. }
  1198. return static_cast<int>(rhs_chunk.empty()) -
  1199. static_cast<int>(lhs_chunk.empty());
  1200. }
  1201. inline absl::string_view Cord::GetFirstChunk(const Cord& c) {
  1202. return c.contents_.FindFlatStartPiece();
  1203. }
  1204. inline absl::string_view Cord::GetFirstChunk(absl::string_view sv) {
  1205. return sv;
  1206. }
  1207. // Compares up to 'size_to_compare' bytes of 'lhs' with 'rhs'. It is assumed
  1208. // that 'size_to_compare' is greater that size of smallest of first chunks.
  1209. template <typename ResultType, typename RHS>
  1210. ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
  1211. size_t size_to_compare) {
  1212. absl::string_view lhs_chunk = Cord::GetFirstChunk(lhs);
  1213. absl::string_view rhs_chunk = Cord::GetFirstChunk(rhs);
  1214. size_t compared_size = std::min(lhs_chunk.size(), rhs_chunk.size());
  1215. assert(size_to_compare >= compared_size);
  1216. int memcmp_res = ::memcmp(lhs_chunk.data(), rhs_chunk.data(), compared_size);
  1217. if (compared_size == size_to_compare || memcmp_res != 0) {
  1218. return ComputeCompareResult<ResultType>(memcmp_res);
  1219. }
  1220. return ComputeCompareResult<ResultType>(
  1221. lhs.CompareSlowPath(rhs, compared_size, size_to_compare));
  1222. }
  1223. bool Cord::EqualsImpl(absl::string_view rhs, size_t size_to_compare) const {
  1224. return GenericCompare<bool>(*this, rhs, size_to_compare);
  1225. }
  1226. bool Cord::EqualsImpl(const Cord& rhs, size_t size_to_compare) const {
  1227. return GenericCompare<bool>(*this, rhs, size_to_compare);
  1228. }
  1229. template <typename RHS>
  1230. inline int SharedCompareImpl(const Cord& lhs, const RHS& rhs) {
  1231. size_t lhs_size = lhs.size();
  1232. size_t rhs_size = rhs.size();
  1233. if (lhs_size == rhs_size) {
  1234. return GenericCompare<int>(lhs, rhs, lhs_size);
  1235. }
  1236. if (lhs_size < rhs_size) {
  1237. auto data_comp_res = GenericCompare<int>(lhs, rhs, lhs_size);
  1238. return data_comp_res == 0 ? -1 : data_comp_res;
  1239. }
  1240. auto data_comp_res = GenericCompare<int>(lhs, rhs, rhs_size);
  1241. return data_comp_res == 0 ? +1 : data_comp_res;
  1242. }
  1243. int Cord::Compare(absl::string_view rhs) const {
  1244. return SharedCompareImpl(*this, rhs);
  1245. }
  1246. int Cord::CompareImpl(const Cord& rhs) const {
  1247. return SharedCompareImpl(*this, rhs);
  1248. }
  1249. bool Cord::EndsWith(absl::string_view rhs) const {
  1250. size_t my_size = size();
  1251. size_t rhs_size = rhs.size();
  1252. if (my_size < rhs_size) return false;
  1253. Cord tmp(*this);
  1254. tmp.RemovePrefix(my_size - rhs_size);
  1255. return tmp.EqualsImpl(rhs, rhs_size);
  1256. }
  1257. bool Cord::EndsWith(const Cord& rhs) const {
  1258. size_t my_size = size();
  1259. size_t rhs_size = rhs.size();
  1260. if (my_size < rhs_size) return false;
  1261. Cord tmp(*this);
  1262. tmp.RemovePrefix(my_size - rhs_size);
  1263. return tmp.EqualsImpl(rhs, rhs_size);
  1264. }
  1265. // --------------------------------------------------------------------
  1266. // Misc.
  1267. Cord::operator std::string() const {
  1268. std::string s;
  1269. absl::CopyCordToString(*this, &s);
  1270. return s;
  1271. }
  1272. void CopyCordToString(const Cord& src, std::string* dst) {
  1273. if (!src.contents_.is_tree()) {
  1274. src.contents_.CopyTo(dst);
  1275. } else {
  1276. absl::strings_internal::STLStringResizeUninitialized(dst, src.size());
  1277. src.CopyToArraySlowPath(&(*dst)[0]);
  1278. }
  1279. }
  1280. void Cord::CopyToArraySlowPath(char* dst) const {
  1281. assert(contents_.is_tree());
  1282. absl::string_view fragment;
  1283. if (GetFlatAux(contents_.tree(), &fragment)) {
  1284. memcpy(dst, fragment.data(), fragment.size());
  1285. return;
  1286. }
  1287. for (absl::string_view chunk : Chunks()) {
  1288. memcpy(dst, chunk.data(), chunk.size());
  1289. dst += chunk.size();
  1290. }
  1291. }
  1292. Cord::ChunkIterator& Cord::ChunkIterator::AdvanceStack() {
  1293. auto& stack_of_right_children = stack_of_right_children_;
  1294. if (stack_of_right_children.empty()) {
  1295. assert(!current_chunk_.empty()); // Called on invalid iterator.
  1296. // We have reached the end of the Cord.
  1297. return *this;
  1298. }
  1299. // Process the next node on the stack.
  1300. CordRep* node = stack_of_right_children.back();
  1301. stack_of_right_children.pop_back();
  1302. // Walk down the left branches until we hit a non-CONCAT node. Save the
  1303. // right children to the stack for subsequent traversal.
  1304. while (node->IsConcat()) {
  1305. stack_of_right_children.push_back(node->concat()->right);
  1306. node = node->concat()->left;
  1307. }
  1308. // Get the child node if we encounter a SUBSTRING.
  1309. size_t offset = 0;
  1310. size_t length = node->length;
  1311. if (node->IsSubstring()) {
  1312. offset = node->substring()->start;
  1313. node = node->substring()->child;
  1314. }
  1315. assert(node->IsExternal() || node->IsFlat());
  1316. assert(length != 0);
  1317. const char* data =
  1318. node->IsExternal() ? node->external()->base : node->flat()->Data();
  1319. current_chunk_ = absl::string_view(data + offset, length);
  1320. current_leaf_ = node;
  1321. return *this;
  1322. }
  1323. Cord Cord::ChunkIterator::AdvanceAndReadBytes(size_t n) {
  1324. ABSL_HARDENING_ASSERT(bytes_remaining_ >= n &&
  1325. "Attempted to iterate past `end()`");
  1326. Cord subcord;
  1327. auto constexpr method = CordzUpdateTracker::kCordReader;
  1328. if (n <= InlineRep::kMaxInline) {
  1329. // Range to read fits in inline data. Flatten it.
  1330. char* data = subcord.contents_.set_data(n);
  1331. while (n > current_chunk_.size()) {
  1332. memcpy(data, current_chunk_.data(), current_chunk_.size());
  1333. data += current_chunk_.size();
  1334. n -= current_chunk_.size();
  1335. ++*this;
  1336. }
  1337. memcpy(data, current_chunk_.data(), n);
  1338. if (n < current_chunk_.size()) {
  1339. RemoveChunkPrefix(n);
  1340. } else if (n > 0) {
  1341. ++*this;
  1342. }
  1343. return subcord;
  1344. }
  1345. if (btree_reader_) {
  1346. size_t chunk_size = current_chunk_.size();
  1347. if (n <= chunk_size && n <= kMaxBytesToCopy) {
  1348. subcord = Cord(current_chunk_.substr(0, n), method);
  1349. if (n < chunk_size) {
  1350. current_chunk_.remove_prefix(n);
  1351. } else {
  1352. current_chunk_ = btree_reader_.Next();
  1353. }
  1354. } else {
  1355. CordRep* rep;
  1356. current_chunk_ = btree_reader_.Read(n, chunk_size, rep);
  1357. subcord.contents_.EmplaceTree(rep, method);
  1358. }
  1359. bytes_remaining_ -= n;
  1360. return subcord;
  1361. }
  1362. auto& stack_of_right_children = stack_of_right_children_;
  1363. if (n < current_chunk_.size()) {
  1364. // Range to read is a proper subrange of the current chunk.
  1365. assert(current_leaf_ != nullptr);
  1366. CordRep* subnode = CordRep::Ref(current_leaf_);
  1367. const char* data = subnode->IsExternal() ? subnode->external()->base
  1368. : subnode->flat()->Data();
  1369. subnode = NewSubstring(subnode, current_chunk_.data() - data, n);
  1370. subcord.contents_.EmplaceTree(VerifyTree(subnode), method);
  1371. RemoveChunkPrefix(n);
  1372. return subcord;
  1373. }
  1374. // Range to read begins with a proper subrange of the current chunk.
  1375. assert(!current_chunk_.empty());
  1376. assert(current_leaf_ != nullptr);
  1377. CordRep* subnode = CordRep::Ref(current_leaf_);
  1378. if (current_chunk_.size() < subnode->length) {
  1379. const char* data = subnode->IsExternal() ? subnode->external()->base
  1380. : subnode->flat()->Data();
  1381. subnode = NewSubstring(subnode, current_chunk_.data() - data,
  1382. current_chunk_.size());
  1383. }
  1384. n -= current_chunk_.size();
  1385. bytes_remaining_ -= current_chunk_.size();
  1386. // Process the next node(s) on the stack, reading whole subtrees depending on
  1387. // their length and how many bytes we are advancing.
  1388. CordRep* node = nullptr;
  1389. while (!stack_of_right_children.empty()) {
  1390. node = stack_of_right_children.back();
  1391. stack_of_right_children.pop_back();
  1392. if (node->length > n) break;
  1393. // TODO(qrczak): This might unnecessarily recreate existing concat nodes.
  1394. // Avoiding that would need pretty complicated logic (instead of
  1395. // current_leaf, keep current_subtree_ which points to the highest node
  1396. // such that the current leaf can be found on the path of left children
  1397. // starting from current_subtree_; delay creating subnode while node is
  1398. // below current_subtree_; find the proper node along the path of left
  1399. // children starting from current_subtree_ if this loop exits while staying
  1400. // below current_subtree_; etc.; alternatively, push parents instead of
  1401. // right children on the stack).
  1402. subnode = Concat(subnode, CordRep::Ref(node));
  1403. n -= node->length;
  1404. bytes_remaining_ -= node->length;
  1405. node = nullptr;
  1406. }
  1407. if (node == nullptr) {
  1408. // We have reached the end of the Cord.
  1409. assert(bytes_remaining_ == 0);
  1410. subcord.contents_.EmplaceTree(VerifyTree(subnode), method);
  1411. return subcord;
  1412. }
  1413. // Walk down the appropriate branches until we hit a non-CONCAT node. Save the
  1414. // right children to the stack for subsequent traversal.
  1415. while (node->IsConcat()) {
  1416. if (node->concat()->left->length > n) {
  1417. // Push right, descend left.
  1418. stack_of_right_children.push_back(node->concat()->right);
  1419. node = node->concat()->left;
  1420. } else {
  1421. // Read left, descend right.
  1422. subnode = Concat(subnode, CordRep::Ref(node->concat()->left));
  1423. n -= node->concat()->left->length;
  1424. bytes_remaining_ -= node->concat()->left->length;
  1425. node = node->concat()->right;
  1426. }
  1427. }
  1428. // Get the child node if we encounter a SUBSTRING.
  1429. size_t offset = 0;
  1430. size_t length = node->length;
  1431. if (node->IsSubstring()) {
  1432. offset = node->substring()->start;
  1433. node = node->substring()->child;
  1434. }
  1435. // Range to read ends with a proper (possibly empty) subrange of the current
  1436. // chunk.
  1437. assert(node->IsExternal() || node->IsFlat());
  1438. assert(length > n);
  1439. if (n > 0) {
  1440. subnode = Concat(subnode, NewSubstring(CordRep::Ref(node), offset, n));
  1441. }
  1442. const char* data =
  1443. node->IsExternal() ? node->external()->base : node->flat()->Data();
  1444. current_chunk_ = absl::string_view(data + offset + n, length - n);
  1445. current_leaf_ = node;
  1446. bytes_remaining_ -= n;
  1447. subcord.contents_.EmplaceTree(VerifyTree(subnode), method);
  1448. return subcord;
  1449. }
  1450. void Cord::ChunkIterator::AdvanceBytesSlowPath(size_t n) {
  1451. assert(bytes_remaining_ >= n && "Attempted to iterate past `end()`");
  1452. assert(n >= current_chunk_.size()); // This should only be called when
  1453. // iterating to a new node.
  1454. n -= current_chunk_.size();
  1455. bytes_remaining_ -= current_chunk_.size();
  1456. if (stack_of_right_children_.empty()) {
  1457. // We have reached the end of the Cord.
  1458. assert(bytes_remaining_ == 0);
  1459. return;
  1460. }
  1461. // Process the next node(s) on the stack, skipping whole subtrees depending on
  1462. // their length and how many bytes we are advancing.
  1463. CordRep* node = nullptr;
  1464. auto& stack_of_right_children = stack_of_right_children_;
  1465. while (!stack_of_right_children.empty()) {
  1466. node = stack_of_right_children.back();
  1467. stack_of_right_children.pop_back();
  1468. if (node->length > n) break;
  1469. n -= node->length;
  1470. bytes_remaining_ -= node->length;
  1471. node = nullptr;
  1472. }
  1473. if (node == nullptr) {
  1474. // We have reached the end of the Cord.
  1475. assert(bytes_remaining_ == 0);
  1476. return;
  1477. }
  1478. // Walk down the appropriate branches until we hit a non-CONCAT node. Save the
  1479. // right children to the stack for subsequent traversal.
  1480. while (node->IsConcat()) {
  1481. if (node->concat()->left->length > n) {
  1482. // Push right, descend left.
  1483. stack_of_right_children.push_back(node->concat()->right);
  1484. node = node->concat()->left;
  1485. } else {
  1486. // Skip left, descend right.
  1487. n -= node->concat()->left->length;
  1488. bytes_remaining_ -= node->concat()->left->length;
  1489. node = node->concat()->right;
  1490. }
  1491. }
  1492. // Get the child node if we encounter a SUBSTRING.
  1493. size_t offset = 0;
  1494. size_t length = node->length;
  1495. if (node->IsSubstring()) {
  1496. offset = node->substring()->start;
  1497. node = node->substring()->child;
  1498. }
  1499. assert(node->IsExternal() || node->IsFlat());
  1500. assert(length > n);
  1501. const char* data =
  1502. node->IsExternal() ? node->external()->base : node->flat()->Data();
  1503. current_chunk_ = absl::string_view(data + offset + n, length - n);
  1504. current_leaf_ = node;
  1505. bytes_remaining_ -= n;
  1506. }
  1507. char Cord::operator[](size_t i) const {
  1508. ABSL_HARDENING_ASSERT(i < size());
  1509. size_t offset = i;
  1510. const CordRep* rep = contents_.tree();
  1511. if (rep == nullptr) {
  1512. return contents_.data()[i];
  1513. }
  1514. while (true) {
  1515. assert(rep != nullptr);
  1516. assert(offset < rep->length);
  1517. if (rep->IsFlat()) {
  1518. // Get the "i"th character directly from the flat array.
  1519. return rep->flat()->Data()[offset];
  1520. } else if (rep->IsBtree()) {
  1521. return rep->btree()->GetCharacter(offset);
  1522. } else if (rep->IsExternal()) {
  1523. // Get the "i"th character from the external array.
  1524. return rep->external()->base[offset];
  1525. } else if (rep->IsConcat()) {
  1526. // Recursively branch to the side of the concatenation that the "i"th
  1527. // character is on.
  1528. size_t left_length = rep->concat()->left->length;
  1529. if (offset < left_length) {
  1530. rep = rep->concat()->left;
  1531. } else {
  1532. offset -= left_length;
  1533. rep = rep->concat()->right;
  1534. }
  1535. } else {
  1536. // This must be a substring a node, so bypass it to get to the child.
  1537. assert(rep->IsSubstring());
  1538. offset += rep->substring()->start;
  1539. rep = rep->substring()->child;
  1540. }
  1541. }
  1542. }
  1543. absl::string_view Cord::FlattenSlowPath() {
  1544. assert(contents_.is_tree());
  1545. size_t total_size = size();
  1546. CordRep* new_rep;
  1547. char* new_buffer;
  1548. // Try to put the contents into a new flat rep. If they won't fit in the
  1549. // biggest possible flat node, use an external rep instead.
  1550. if (total_size <= kMaxFlatLength) {
  1551. new_rep = CordRepFlat::New(total_size);
  1552. new_rep->length = total_size;
  1553. new_buffer = new_rep->flat()->Data();
  1554. CopyToArraySlowPath(new_buffer);
  1555. } else {
  1556. new_buffer = std::allocator<char>().allocate(total_size);
  1557. CopyToArraySlowPath(new_buffer);
  1558. new_rep = absl::cord_internal::NewExternalRep(
  1559. absl::string_view(new_buffer, total_size), [](absl::string_view s) {
  1560. std::allocator<char>().deallocate(const_cast<char*>(s.data()),
  1561. s.size());
  1562. });
  1563. }
  1564. CordzUpdateScope scope(contents_.cordz_info(), CordzUpdateTracker::kFlatten);
  1565. CordRep::Unref(contents_.as_tree());
  1566. contents_.SetTree(new_rep, scope);
  1567. return absl::string_view(new_buffer, total_size);
  1568. }
  1569. /* static */ bool Cord::GetFlatAux(CordRep* rep, absl::string_view* fragment) {
  1570. assert(rep != nullptr);
  1571. if (rep->IsFlat()) {
  1572. *fragment = absl::string_view(rep->flat()->Data(), rep->length);
  1573. return true;
  1574. } else if (rep->IsExternal()) {
  1575. *fragment = absl::string_view(rep->external()->base, rep->length);
  1576. return true;
  1577. } else if (rep->IsBtree()) {
  1578. return rep->btree()->IsFlat(fragment);
  1579. } else if (rep->IsSubstring()) {
  1580. CordRep* child = rep->substring()->child;
  1581. if (child->IsFlat()) {
  1582. *fragment = absl::string_view(
  1583. child->flat()->Data() + rep->substring()->start, rep->length);
  1584. return true;
  1585. } else if (child->IsExternal()) {
  1586. *fragment = absl::string_view(
  1587. child->external()->base + rep->substring()->start, rep->length);
  1588. return true;
  1589. } else if (child->IsBtree()) {
  1590. return child->btree()->IsFlat(rep->substring()->start, rep->length,
  1591. fragment);
  1592. }
  1593. }
  1594. return false;
  1595. }
  1596. /* static */ void Cord::ForEachChunkAux(
  1597. absl::cord_internal::CordRep* rep,
  1598. absl::FunctionRef<void(absl::string_view)> callback) {
  1599. if (rep->IsBtree()) {
  1600. ChunkIterator it(rep), end;
  1601. while (it != end) {
  1602. callback(*it);
  1603. ++it;
  1604. }
  1605. return;
  1606. }
  1607. assert(rep != nullptr);
  1608. int stack_pos = 0;
  1609. constexpr int stack_max = 128;
  1610. // Stack of right branches for tree traversal
  1611. absl::cord_internal::CordRep* stack[stack_max];
  1612. absl::cord_internal::CordRep* current_node = rep;
  1613. while (true) {
  1614. if (current_node->IsConcat()) {
  1615. if (stack_pos == stack_max) {
  1616. // There's no more room on our stack array to add another right branch,
  1617. // and the idea is to avoid allocations, so call this function
  1618. // recursively to navigate this subtree further. (This is not something
  1619. // we expect to happen in practice).
  1620. ForEachChunkAux(current_node, callback);
  1621. // Pop the next right branch and iterate.
  1622. current_node = stack[--stack_pos];
  1623. continue;
  1624. } else {
  1625. // Save the right branch for later traversal and continue down the left
  1626. // branch.
  1627. stack[stack_pos++] = current_node->concat()->right;
  1628. current_node = current_node->concat()->left;
  1629. continue;
  1630. }
  1631. }
  1632. // This is a leaf node, so invoke our callback.
  1633. absl::string_view chunk;
  1634. bool success = GetFlatAux(current_node, &chunk);
  1635. assert(success);
  1636. if (success) {
  1637. callback(chunk);
  1638. }
  1639. if (stack_pos == 0) {
  1640. // end of traversal
  1641. return;
  1642. }
  1643. current_node = stack[--stack_pos];
  1644. }
  1645. }
  1646. static void DumpNode(CordRep* rep, bool include_data, std::ostream* os,
  1647. int indent) {
  1648. const int kIndentStep = 1;
  1649. absl::InlinedVector<CordRep*, kInlinedVectorSize> stack;
  1650. absl::InlinedVector<int, kInlinedVectorSize> indents;
  1651. for (;;) {
  1652. *os << std::setw(3) << rep->refcount.Get();
  1653. *os << " " << std::setw(7) << rep->length;
  1654. *os << " [";
  1655. if (include_data) *os << static_cast<void*>(rep);
  1656. *os << "]";
  1657. *os << " " << (IsRootBalanced(rep) ? 'b' : 'u');
  1658. *os << " " << std::setw(indent) << "";
  1659. if (rep->IsConcat()) {
  1660. *os << "CONCAT depth=" << Depth(rep) << "\n";
  1661. indent += kIndentStep;
  1662. indents.push_back(indent);
  1663. stack.push_back(rep->concat()->right);
  1664. rep = rep->concat()->left;
  1665. } else if (rep->IsSubstring()) {
  1666. *os << "SUBSTRING @ " << rep->substring()->start << "\n";
  1667. indent += kIndentStep;
  1668. rep = rep->substring()->child;
  1669. } else { // Leaf or ring
  1670. if (rep->IsExternal()) {
  1671. *os << "EXTERNAL [";
  1672. if (include_data)
  1673. *os << absl::CEscape(std::string(rep->external()->base, rep->length));
  1674. *os << "]\n";
  1675. } else if (rep->IsFlat()) {
  1676. *os << "FLAT cap=" << rep->flat()->Capacity() << " [";
  1677. if (include_data)
  1678. *os << absl::CEscape(std::string(rep->flat()->Data(), rep->length));
  1679. *os << "]\n";
  1680. } else {
  1681. CordRepBtree::Dump(rep, /*label=*/ "", include_data, *os);
  1682. }
  1683. if (stack.empty()) break;
  1684. rep = stack.back();
  1685. stack.pop_back();
  1686. indent = indents.back();
  1687. indents.pop_back();
  1688. }
  1689. }
  1690. ABSL_INTERNAL_CHECK(indents.empty(), "");
  1691. }
  1692. static std::string ReportError(CordRep* root, CordRep* node) {
  1693. std::ostringstream buf;
  1694. buf << "Error at node " << node << " in:";
  1695. DumpNode(root, true, &buf);
  1696. return buf.str();
  1697. }
  1698. static bool VerifyNode(CordRep* root, CordRep* start_node,
  1699. bool full_validation) {
  1700. absl::InlinedVector<CordRep*, 2> worklist;
  1701. worklist.push_back(start_node);
  1702. do {
  1703. CordRep* node = worklist.back();
  1704. worklist.pop_back();
  1705. ABSL_INTERNAL_CHECK(node != nullptr, ReportError(root, node));
  1706. if (node != root) {
  1707. ABSL_INTERNAL_CHECK(node->length != 0, ReportError(root, node));
  1708. }
  1709. if (node->IsConcat()) {
  1710. ABSL_INTERNAL_CHECK(node->concat()->left != nullptr,
  1711. ReportError(root, node));
  1712. ABSL_INTERNAL_CHECK(node->concat()->right != nullptr,
  1713. ReportError(root, node));
  1714. ABSL_INTERNAL_CHECK((node->length == node->concat()->left->length +
  1715. node->concat()->right->length),
  1716. ReportError(root, node));
  1717. if (full_validation) {
  1718. worklist.push_back(node->concat()->right);
  1719. worklist.push_back(node->concat()->left);
  1720. }
  1721. } else if (node->IsFlat()) {
  1722. ABSL_INTERNAL_CHECK(node->length <= node->flat()->Capacity(),
  1723. ReportError(root, node));
  1724. } else if (node->IsExternal()) {
  1725. ABSL_INTERNAL_CHECK(node->external()->base != nullptr,
  1726. ReportError(root, node));
  1727. } else if (node->IsSubstring()) {
  1728. ABSL_INTERNAL_CHECK(
  1729. node->substring()->start < node->substring()->child->length,
  1730. ReportError(root, node));
  1731. ABSL_INTERNAL_CHECK(node->substring()->start + node->length <=
  1732. node->substring()->child->length,
  1733. ReportError(root, node));
  1734. }
  1735. } while (!worklist.empty());
  1736. return true;
  1737. }
  1738. // Traverses the tree and computes the total memory allocated.
  1739. /* static */ size_t Cord::MemoryUsageAux(const CordRep* rep) {
  1740. size_t total_mem_usage = 0;
  1741. // Allow a quick exit for the common case that the root is a leaf.
  1742. if (RepMemoryUsageLeaf(rep, &total_mem_usage)) {
  1743. return total_mem_usage;
  1744. }
  1745. // Iterate over the tree. cur_node is never a leaf node and leaf nodes will
  1746. // never be appended to tree_stack. This reduces overhead from manipulating
  1747. // tree_stack.
  1748. absl::InlinedVector<const CordRep*, kInlinedVectorSize> tree_stack;
  1749. const CordRep* cur_node = rep;
  1750. while (true) {
  1751. const CordRep* next_node = nullptr;
  1752. if (cur_node->IsConcat()) {
  1753. total_mem_usage += sizeof(CordRepConcat);
  1754. const CordRep* left = cur_node->concat()->left;
  1755. if (!RepMemoryUsageLeaf(left, &total_mem_usage)) {
  1756. next_node = left;
  1757. }
  1758. const CordRep* right = cur_node->concat()->right;
  1759. if (!RepMemoryUsageLeaf(right, &total_mem_usage)) {
  1760. if (next_node) {
  1761. tree_stack.push_back(next_node);
  1762. }
  1763. next_node = right;
  1764. }
  1765. } else if (cur_node->IsBtree()) {
  1766. total_mem_usage += sizeof(CordRepBtree);
  1767. const CordRepBtree* node = cur_node->btree();
  1768. if (node->height() == 0) {
  1769. for (const CordRep* edge : node->Edges()) {
  1770. RepMemoryUsageDataEdge(edge, &total_mem_usage);
  1771. }
  1772. } else {
  1773. for (const CordRep* edge : node->Edges()) {
  1774. tree_stack.push_back(edge);
  1775. }
  1776. }
  1777. } else {
  1778. // Since cur_node is not a leaf or a concat node it must be a substring.
  1779. assert(cur_node->IsSubstring());
  1780. total_mem_usage += sizeof(CordRepSubstring);
  1781. next_node = cur_node->substring()->child;
  1782. if (RepMemoryUsageLeaf(next_node, &total_mem_usage)) {
  1783. next_node = nullptr;
  1784. }
  1785. }
  1786. if (!next_node) {
  1787. if (tree_stack.empty()) {
  1788. return total_mem_usage;
  1789. }
  1790. next_node = tree_stack.back();
  1791. tree_stack.pop_back();
  1792. }
  1793. cur_node = next_node;
  1794. }
  1795. }
  1796. std::ostream& operator<<(std::ostream& out, const Cord& cord) {
  1797. for (absl::string_view chunk : cord.Chunks()) {
  1798. out.write(chunk.data(), chunk.size());
  1799. }
  1800. return out;
  1801. }
  1802. namespace strings_internal {
  1803. size_t CordTestAccess::FlatOverhead() { return cord_internal::kFlatOverhead; }
  1804. size_t CordTestAccess::MaxFlatLength() { return cord_internal::kMaxFlatLength; }
  1805. size_t CordTestAccess::FlatTagToLength(uint8_t tag) {
  1806. return cord_internal::TagToLength(tag);
  1807. }
  1808. uint8_t CordTestAccess::LengthToTag(size_t s) {
  1809. ABSL_INTERNAL_CHECK(s <= kMaxFlatLength, absl::StrCat("Invalid length ", s));
  1810. return cord_internal::AllocatedSizeToTag(s + cord_internal::kFlatOverhead);
  1811. }
  1812. size_t CordTestAccess::SizeofCordRepConcat() { return sizeof(CordRepConcat); }
  1813. size_t CordTestAccess::SizeofCordRepExternal() {
  1814. return sizeof(CordRepExternal);
  1815. }
  1816. size_t CordTestAccess::SizeofCordRepSubstring() {
  1817. return sizeof(CordRepSubstring);
  1818. }
  1819. } // namespace strings_internal
  1820. ABSL_NAMESPACE_END
  1821. } // namespace absl