cord.h 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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. //
  15. // -----------------------------------------------------------------------------
  16. // File: cord.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This file defines the `absl::Cord` data structure and operations on that data
  20. // structure. A Cord is a string-like sequence of characters optimized for
  21. // specific use cases. Unlike a `std::string`, which stores an array of
  22. // contiguous characters, Cord data is stored in a structure consisting of
  23. // separate, reference-counted "chunks."
  24. //
  25. // Because a Cord consists of these chunks, data can be added to or removed from
  26. // a Cord during its lifetime. Chunks may also be shared between Cords. Unlike a
  27. // `std::string`, a Cord can therefore accommodate data that changes over its
  28. // lifetime, though it's not quite "mutable"; it can change only in the
  29. // attachment, detachment, or rearrangement of chunks of its constituent data.
  30. //
  31. // A Cord provides some benefit over `std::string` under the following (albeit
  32. // narrow) circumstances:
  33. //
  34. // * Cord data is designed to grow and shrink over a Cord's lifetime. Cord
  35. // provides efficient insertions and deletions at the start and end of the
  36. // character sequences, avoiding copies in those cases. Static data should
  37. // generally be stored as strings.
  38. // * External memory consisting of string-like data can be directly added to
  39. // a Cord without requiring copies or allocations.
  40. // * Cord data may be shared and copied cheaply. Cord provides a copy-on-write
  41. // implementation and cheap sub-Cord operations. Copying a Cord is an O(1)
  42. // operation.
  43. //
  44. // As a consequence to the above, Cord data is generally large. Small data
  45. // should generally use strings, as construction of a Cord requires some
  46. // overhead. Small Cords (<= 15 bytes) are represented inline, but most small
  47. // Cords are expected to grow over their lifetimes.
  48. //
  49. // Note that because a Cord is made up of separate chunked data, random access
  50. // to character data within a Cord is slower than within a `std::string`.
  51. //
  52. // Thread Safety
  53. //
  54. // Cord has the same thread-safety properties as many other types like
  55. // std::string, std::vector<>, int, etc -- it is thread-compatible. In
  56. // particular, if threads do not call non-const methods, then it is safe to call
  57. // const methods without synchronization. Copying a Cord produces a new instance
  58. // that can be used concurrently with the original in arbitrary ways.
  59. #ifndef ABSL_STRINGS_CORD_H_
  60. #define ABSL_STRINGS_CORD_H_
  61. #include <algorithm>
  62. #include <cassert>
  63. #include <cstddef>
  64. #include <cstdint>
  65. #include <cstring>
  66. #include <iosfwd>
  67. #include <iterator>
  68. #include <string>
  69. #include <type_traits>
  70. #include <utility>
  71. #include "absl/base/attributes.h"
  72. #include "absl/base/config.h"
  73. #include "absl/base/internal/endian.h"
  74. #include "absl/base/macros.h"
  75. #include "absl/base/nullability.h"
  76. #include "absl/base/optimization.h"
  77. #include "absl/crc/internal/crc_cord_state.h"
  78. #include "absl/functional/function_ref.h"
  79. #include "absl/meta/type_traits.h"
  80. #include "absl/strings/cord_analysis.h"
  81. #include "absl/strings/cord_buffer.h"
  82. #include "absl/strings/internal/cord_data_edge.h"
  83. #include "absl/strings/internal/cord_internal.h"
  84. #include "absl/strings/internal/cord_rep_btree.h"
  85. #include "absl/strings/internal/cord_rep_btree_reader.h"
  86. #include "absl/strings/internal/cord_rep_crc.h"
  87. #include "absl/strings/internal/cord_rep_flat.h"
  88. #include "absl/strings/internal/cordz_info.h"
  89. #include "absl/strings/internal/cordz_update_scope.h"
  90. #include "absl/strings/internal/cordz_update_tracker.h"
  91. #include "absl/strings/internal/string_constant.h"
  92. #include "absl/strings/string_view.h"
  93. #include "absl/types/compare.h"
  94. #include "absl/types/optional.h"
  95. namespace absl {
  96. ABSL_NAMESPACE_BEGIN
  97. class Cord;
  98. class CordTestPeer;
  99. template <typename Releaser>
  100. Cord MakeCordFromExternal(absl::string_view, Releaser&&);
  101. void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
  102. void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
  103. // Cord memory accounting modes
  104. enum class CordMemoryAccounting {
  105. // Counts the *approximate* number of bytes held in full or in part by this
  106. // Cord (which may not remain the same between invocations). Cords that share
  107. // memory could each be "charged" independently for the same shared memory.
  108. // See also comment on `kTotalMorePrecise` on internally shared memory.
  109. kTotal,
  110. // Counts the *approximate* number of bytes held in full or in part by this
  111. // Cord for the distinct memory held by this cord. This option is similar
  112. // to `kTotal`, except that if the cord has multiple references to the same
  113. // memory, that memory is only counted once.
  114. //
  115. // For example:
  116. // absl::Cord cord;
  117. // cord.Append(some_other_cord);
  118. // cord.Append(some_other_cord);
  119. // // Counts `some_other_cord` twice:
  120. // cord.EstimatedMemoryUsage(kTotal);
  121. // // Counts `some_other_cord` once:
  122. // cord.EstimatedMemoryUsage(kTotalMorePrecise);
  123. //
  124. // The `kTotalMorePrecise` number is more expensive to compute as it requires
  125. // deduplicating all memory references. Applications should prefer to use
  126. // `kFairShare` or `kTotal` unless they really need a more precise estimate
  127. // on "how much memory is potentially held / kept alive by this cord?"
  128. kTotalMorePrecise,
  129. // Counts the *approximate* number of bytes held in full or in part by this
  130. // Cord weighted by the sharing ratio of that data. For example, if some data
  131. // edge is shared by 4 different Cords, then each cord is attributed 1/4th of
  132. // the total memory usage as a 'fair share' of the total memory usage.
  133. kFairShare,
  134. };
  135. // Cord
  136. //
  137. // A Cord is a sequence of characters, designed to be more efficient than a
  138. // `std::string` in certain circumstances: namely, large string data that needs
  139. // to change over its lifetime or shared, especially when such data is shared
  140. // across API boundaries.
  141. //
  142. // A Cord stores its character data in a structure that allows efficient prepend
  143. // and append operations. This makes a Cord useful for large string data sent
  144. // over in a wire format that may need to be prepended or appended at some point
  145. // during the data exchange (e.g. HTTP, protocol buffers). For example, a
  146. // Cord is useful for storing an HTTP request, and prepending an HTTP header to
  147. // such a request.
  148. //
  149. // Cords should not be used for storing general string data, however. They
  150. // require overhead to construct and are slower than strings for random access.
  151. //
  152. // The Cord API provides the following common API operations:
  153. //
  154. // * Create or assign Cords out of existing string data, memory, or other Cords
  155. // * Append and prepend data to an existing Cord
  156. // * Create new Sub-Cords from existing Cord data
  157. // * Swap Cord data and compare Cord equality
  158. // * Write out Cord data by constructing a `std::string`
  159. //
  160. // Additionally, the API provides iterator utilities to iterate through Cord
  161. // data via chunks or character bytes.
  162. //
  163. class Cord {
  164. private:
  165. template <typename T>
  166. using EnableIfString =
  167. absl::enable_if_t<std::is_same<T, std::string>::value, int>;
  168. public:
  169. // Cord::Cord() Constructors.
  170. // Creates an empty Cord.
  171. constexpr Cord() noexcept;
  172. // Creates a Cord from an existing Cord. Cord is copyable and efficiently
  173. // movable. The moved-from state is valid but unspecified.
  174. Cord(const Cord& src);
  175. Cord(Cord&& src) noexcept;
  176. Cord& operator=(const Cord& x);
  177. Cord& operator=(Cord&& x) noexcept;
  178. // Creates a Cord from a `src` string. This constructor is marked explicit to
  179. // prevent implicit Cord constructions from arguments convertible to an
  180. // `absl::string_view`.
  181. explicit Cord(absl::string_view src);
  182. Cord& operator=(absl::string_view src);
  183. // Creates a Cord from a `std::string&&` rvalue. These constructors are
  184. // templated to avoid ambiguities for types that are convertible to both
  185. // `absl::string_view` and `std::string`, such as `const char*`.
  186. template <typename T, EnableIfString<T> = 0>
  187. explicit Cord(T&& src);
  188. template <typename T, EnableIfString<T> = 0>
  189. Cord& operator=(T&& src);
  190. // Cord::~Cord()
  191. //
  192. // Destructs the Cord.
  193. ~Cord() {
  194. if (contents_.is_tree()) DestroyCordSlow();
  195. }
  196. // MakeCordFromExternal()
  197. //
  198. // Creates a Cord that takes ownership of external string memory. The
  199. // contents of `data` are not copied to the Cord; instead, the external
  200. // memory is added to the Cord and reference-counted. This data may not be
  201. // changed for the life of the Cord, though it may be prepended or appended
  202. // to.
  203. //
  204. // `MakeCordFromExternal()` takes a callable "releaser" that is invoked when
  205. // the reference count for `data` reaches zero. As noted above, this data must
  206. // remain live until the releaser is invoked. The callable releaser also must:
  207. //
  208. // * be move constructible
  209. // * support `void operator()(absl::string_view) const` or `void operator()`
  210. //
  211. // Example:
  212. //
  213. // Cord MakeCord(BlockPool* pool) {
  214. // Block* block = pool->NewBlock();
  215. // FillBlock(block);
  216. // return absl::MakeCordFromExternal(
  217. // block->ToStringView(),
  218. // [pool, block](absl::string_view v) {
  219. // pool->FreeBlock(block, v);
  220. // });
  221. // }
  222. //
  223. // WARNING: Because a Cord can be reference-counted, it's likely a bug if your
  224. // releaser doesn't do anything. For example, consider the following:
  225. //
  226. // void Foo(const char* buffer, int len) {
  227. // auto c = absl::MakeCordFromExternal(absl::string_view(buffer, len),
  228. // [](absl::string_view) {});
  229. //
  230. // // BUG: If Bar() copies its cord for any reason, including keeping a
  231. // // substring of it, the lifetime of buffer might be extended beyond
  232. // // when Foo() returns.
  233. // Bar(c);
  234. // }
  235. template <typename Releaser>
  236. friend Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser);
  237. // Cord::Clear()
  238. //
  239. // Releases the Cord data. Any nodes that share data with other Cords, if
  240. // applicable, will have their reference counts reduced by 1.
  241. ABSL_ATTRIBUTE_REINITIALIZES void Clear();
  242. // Cord::Append()
  243. //
  244. // Appends data to the Cord, which may come from another Cord or other string
  245. // data.
  246. void Append(const Cord& src);
  247. void Append(Cord&& src);
  248. void Append(absl::string_view src);
  249. template <typename T, EnableIfString<T> = 0>
  250. void Append(T&& src);
  251. // Appends `buffer` to this cord, unless `buffer` has a zero length in which
  252. // case this method has no effect on this cord instance.
  253. // This method is guaranteed to consume `buffer`.
  254. void Append(CordBuffer buffer);
  255. // Returns a CordBuffer, re-using potential existing capacity in this cord.
  256. //
  257. // Cord instances may have additional unused capacity in the last (or first)
  258. // nodes of the underlying tree to facilitate amortized growth. This method
  259. // allows applications to explicitly use this spare capacity if available,
  260. // or create a new CordBuffer instance otherwise.
  261. // If this cord has a final non-shared node with at least `min_capacity`
  262. // available, then this method will return that buffer including its data
  263. // contents. I.e.; the returned buffer will have a non-zero length, and
  264. // a capacity of at least `buffer.length + min_capacity`. Otherwise, this
  265. // method will return `CordBuffer::CreateWithDefaultLimit(capacity)`.
  266. //
  267. // Below an example of using GetAppendBuffer. Notice that in this example we
  268. // use `GetAppendBuffer()` only on the first iteration. As we know nothing
  269. // about any initial extra capacity in `cord`, we may be able to use the extra
  270. // capacity. But as we add new buffers with fully utilized contents after that
  271. // we avoid calling `GetAppendBuffer()` on subsequent iterations: while this
  272. // works fine, it results in an unnecessary inspection of cord contents:
  273. //
  274. // void AppendRandomDataToCord(absl::Cord &cord, size_t n) {
  275. // bool first = true;
  276. // while (n > 0) {
  277. // CordBuffer buffer = first ? cord.GetAppendBuffer(n)
  278. // : CordBuffer::CreateWithDefaultLimit(n);
  279. // absl::Span<char> data = buffer.available_up_to(n);
  280. // FillRandomValues(data.data(), data.size());
  281. // buffer.IncreaseLengthBy(data.size());
  282. // cord.Append(std::move(buffer));
  283. // n -= data.size();
  284. // first = false;
  285. // }
  286. // }
  287. CordBuffer GetAppendBuffer(size_t capacity, size_t min_capacity = 16);
  288. // Returns a CordBuffer, re-using potential existing capacity in this cord.
  289. //
  290. // This function is identical to `GetAppendBuffer`, except that in the case
  291. // where a new `CordBuffer` is allocated, it is allocated using the provided
  292. // custom limit instead of the default limit. `GetAppendBuffer` will default
  293. // to `CordBuffer::CreateWithDefaultLimit(capacity)` whereas this method
  294. // will default to `CordBuffer::CreateWithCustomLimit(block_size, capacity)`.
  295. // This method is equivalent to `GetAppendBuffer` if `block_size` is zero.
  296. // See the documentation for `CreateWithCustomLimit` for more details on the
  297. // restrictions and legal values for `block_size`.
  298. CordBuffer GetCustomAppendBuffer(size_t block_size, size_t capacity,
  299. size_t min_capacity = 16);
  300. // Cord::Prepend()
  301. //
  302. // Prepends data to the Cord, which may come from another Cord or other string
  303. // data.
  304. void Prepend(const Cord& src);
  305. void Prepend(absl::string_view src);
  306. template <typename T, EnableIfString<T> = 0>
  307. void Prepend(T&& src);
  308. // Prepends `buffer` to this cord, unless `buffer` has a zero length in which
  309. // case this method has no effect on this cord instance.
  310. // This method is guaranteed to consume `buffer`.
  311. void Prepend(CordBuffer buffer);
  312. // Cord::RemovePrefix()
  313. //
  314. // Removes the first `n` bytes of a Cord.
  315. void RemovePrefix(size_t n);
  316. void RemoveSuffix(size_t n);
  317. // Cord::Subcord()
  318. //
  319. // Returns a new Cord representing the subrange [pos, pos + new_size) of
  320. // *this. If pos >= size(), the result is empty(). If
  321. // (pos + new_size) >= size(), the result is the subrange [pos, size()).
  322. Cord Subcord(size_t pos, size_t new_size) const;
  323. // Cord::swap()
  324. //
  325. // Swaps the contents of the Cord with `other`.
  326. void swap(Cord& other) noexcept;
  327. // swap()
  328. //
  329. // Swaps the contents of two Cords.
  330. friend void swap(Cord& x, Cord& y) noexcept { x.swap(y); }
  331. // Cord::size()
  332. //
  333. // Returns the size of the Cord.
  334. size_t size() const;
  335. // Cord::empty()
  336. //
  337. // Determines whether the given Cord is empty, returning `true` if so.
  338. bool empty() const;
  339. // Cord::EstimatedMemoryUsage()
  340. //
  341. // Returns the *approximate* number of bytes held by this cord.
  342. // See CordMemoryAccounting for more information on the accounting method.
  343. size_t EstimatedMemoryUsage(CordMemoryAccounting accounting_method =
  344. CordMemoryAccounting::kTotal) const;
  345. // Cord::Compare()
  346. //
  347. // Compares 'this' Cord with rhs. This function and its relatives treat Cords
  348. // as sequences of unsigned bytes. The comparison is a straightforward
  349. // lexicographic comparison. `Cord::Compare()` returns values as follows:
  350. //
  351. // -1 'this' Cord is smaller
  352. // 0 two Cords are equal
  353. // 1 'this' Cord is larger
  354. int Compare(absl::string_view rhs) const;
  355. int Compare(const Cord& rhs) const;
  356. // Cord::StartsWith()
  357. //
  358. // Determines whether the Cord starts with the passed string data `rhs`.
  359. bool StartsWith(const Cord& rhs) const;
  360. bool StartsWith(absl::string_view rhs) const;
  361. // Cord::EndsWith()
  362. //
  363. // Determines whether the Cord ends with the passed string data `rhs`.
  364. bool EndsWith(absl::string_view rhs) const;
  365. bool EndsWith(const Cord& rhs) const;
  366. // Cord::Contains()
  367. //
  368. // Determines whether the Cord contains the passed string data `rhs`.
  369. bool Contains(absl::string_view rhs) const;
  370. bool Contains(const Cord& rhs) const;
  371. // Cord::operator std::string()
  372. //
  373. // Converts a Cord into a `std::string()`. This operator is marked explicit to
  374. // prevent unintended Cord usage in functions that take a string.
  375. explicit operator std::string() const;
  376. // CopyCordToString()
  377. //
  378. // Copies the contents of a `src` Cord into a `*dst` string.
  379. //
  380. // This function optimizes the case of reusing the destination string since it
  381. // can reuse previously allocated capacity. However, this function does not
  382. // guarantee that pointers previously returned by `dst->data()` remain valid
  383. // even if `*dst` had enough capacity to hold `src`. If `*dst` is a new
  384. // object, prefer to simply use the conversion operator to `std::string`.
  385. friend void CopyCordToString(const Cord& src,
  386. absl::Nonnull<std::string*> dst);
  387. // AppendCordToString()
  388. //
  389. // Appends the contents of a `src` Cord to a `*dst` string.
  390. //
  391. // This function optimizes the case of appending to a non-empty destination
  392. // string. If `*dst` already has capacity to store the contents of the cord,
  393. // this function does not invalidate pointers previously returned by
  394. // `dst->data()`. If `*dst` is a new object, prefer to simply use the
  395. // conversion operator to `std::string`.
  396. friend void AppendCordToString(const Cord& src,
  397. absl::Nonnull<std::string*> dst);
  398. class CharIterator;
  399. //----------------------------------------------------------------------------
  400. // Cord::ChunkIterator
  401. //----------------------------------------------------------------------------
  402. //
  403. // A `Cord::ChunkIterator` allows iteration over the constituent chunks of its
  404. // Cord. Such iteration allows you to perform non-const operations on the data
  405. // of a Cord without modifying it.
  406. //
  407. // Generally, you do not instantiate a `Cord::ChunkIterator` directly;
  408. // instead, you create one implicitly through use of the `Cord::Chunks()`
  409. // member function.
  410. //
  411. // The `Cord::ChunkIterator` has the following properties:
  412. //
  413. // * The iterator is invalidated after any non-const operation on the
  414. // Cord object over which it iterates.
  415. // * The `string_view` returned by dereferencing a valid, non-`end()`
  416. // iterator is guaranteed to be non-empty.
  417. // * Two `ChunkIterator` objects can be compared equal if and only if they
  418. // remain valid and iterate over the same Cord.
  419. // * The iterator in this case is a proxy iterator; the `string_view`
  420. // returned by the iterator does not live inside the Cord, and its
  421. // lifetime is limited to the lifetime of the iterator itself. To help
  422. // prevent lifetime issues, `ChunkIterator::reference` is not a true
  423. // reference type and is equivalent to `value_type`.
  424. // * The iterator keeps state that can grow for Cords that contain many
  425. // nodes and are imbalanced due to sharing. Prefer to pass this type by
  426. // const reference instead of by value.
  427. class ChunkIterator {
  428. public:
  429. using iterator_category = std::input_iterator_tag;
  430. using value_type = absl::string_view;
  431. using difference_type = ptrdiff_t;
  432. using pointer = absl::Nonnull<const value_type*>;
  433. using reference = value_type;
  434. ChunkIterator() = default;
  435. ChunkIterator& operator++();
  436. ChunkIterator operator++(int);
  437. bool operator==(const ChunkIterator& other) const;
  438. bool operator!=(const ChunkIterator& other) const;
  439. reference operator*() const;
  440. pointer operator->() const;
  441. friend class Cord;
  442. friend class CharIterator;
  443. private:
  444. using CordRep = absl::cord_internal::CordRep;
  445. using CordRepBtree = absl::cord_internal::CordRepBtree;
  446. using CordRepBtreeReader = absl::cord_internal::CordRepBtreeReader;
  447. // Constructs a `begin()` iterator from `tree`.
  448. explicit ChunkIterator(absl::Nonnull<cord_internal::CordRep*> tree);
  449. // Constructs a `begin()` iterator from `cord`.
  450. explicit ChunkIterator(absl::Nonnull<const Cord*> cord);
  451. // Initializes this instance from a tree. Invoked by constructors.
  452. void InitTree(absl::Nonnull<cord_internal::CordRep*> tree);
  453. // Removes `n` bytes from `current_chunk_`. Expects `n` to be smaller than
  454. // `current_chunk_.size()`.
  455. void RemoveChunkPrefix(size_t n);
  456. Cord AdvanceAndReadBytes(size_t n);
  457. void AdvanceBytes(size_t n);
  458. // Btree specific operator++
  459. ChunkIterator& AdvanceBtree();
  460. void AdvanceBytesBtree(size_t n);
  461. // A view into bytes of the current `CordRep`. It may only be a view to a
  462. // suffix of bytes if this is being used by `CharIterator`.
  463. absl::string_view current_chunk_;
  464. // The current leaf, or `nullptr` if the iterator points to short data.
  465. // If the current chunk is a substring node, current_leaf_ points to the
  466. // underlying flat or external node.
  467. absl::Nullable<absl::cord_internal::CordRep*> current_leaf_ = nullptr;
  468. // The number of bytes left in the `Cord` over which we are iterating.
  469. size_t bytes_remaining_ = 0;
  470. // Cord reader for cord btrees. Empty if not traversing a btree.
  471. CordRepBtreeReader btree_reader_;
  472. };
  473. // Cord::chunk_begin()
  474. //
  475. // Returns an iterator to the first chunk of the `Cord`.
  476. //
  477. // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
  478. // iterating over the chunks of a Cord. This method may be useful for getting
  479. // a `ChunkIterator` where range-based for-loops are not useful.
  480. //
  481. // Example:
  482. //
  483. // absl::Cord::ChunkIterator FindAsChunk(const absl::Cord& c,
  484. // absl::string_view s) {
  485. // return std::find(c.chunk_begin(), c.chunk_end(), s);
  486. // }
  487. ChunkIterator chunk_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  488. // Cord::chunk_end()
  489. //
  490. // Returns an iterator one increment past the last chunk of the `Cord`.
  491. //
  492. // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
  493. // iterating over the chunks of a Cord. This method may be useful for getting
  494. // a `ChunkIterator` where range-based for-loops may not be available.
  495. ChunkIterator chunk_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  496. //----------------------------------------------------------------------------
  497. // Cord::ChunkRange
  498. //----------------------------------------------------------------------------
  499. //
  500. // `ChunkRange` is a helper class for iterating over the chunks of the `Cord`,
  501. // producing an iterator which can be used within a range-based for loop.
  502. // Construction of a `ChunkRange` will return an iterator pointing to the
  503. // first chunk of the Cord. Generally, do not construct a `ChunkRange`
  504. // directly; instead, prefer to use the `Cord::Chunks()` method.
  505. //
  506. // Implementation note: `ChunkRange` is simply a convenience wrapper over
  507. // `Cord::chunk_begin()` and `Cord::chunk_end()`.
  508. class ChunkRange {
  509. public:
  510. // Fulfill minimum c++ container requirements [container.requirements]
  511. // These (partial) container type definitions allow ChunkRange to be used
  512. // in various utilities expecting a subset of [container.requirements].
  513. // For example, the below enables using `::testing::ElementsAre(...)`
  514. using value_type = absl::string_view;
  515. using reference = value_type&;
  516. using const_reference = const value_type&;
  517. using iterator = ChunkIterator;
  518. using const_iterator = ChunkIterator;
  519. explicit ChunkRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
  520. ChunkIterator begin() const;
  521. ChunkIterator end() const;
  522. private:
  523. absl::Nonnull<const Cord*> cord_;
  524. };
  525. // Cord::Chunks()
  526. //
  527. // Returns a `Cord::ChunkRange` for iterating over the chunks of a `Cord` with
  528. // a range-based for-loop. For most iteration tasks on a Cord, use
  529. // `Cord::Chunks()` to retrieve this iterator.
  530. //
  531. // Example:
  532. //
  533. // void ProcessChunks(const Cord& cord) {
  534. // for (absl::string_view chunk : cord.Chunks()) { ... }
  535. // }
  536. //
  537. // Note that the ordinary caveats of temporary lifetime extension apply:
  538. //
  539. // void Process() {
  540. // for (absl::string_view chunk : CordFactory().Chunks()) {
  541. // // The temporary Cord returned by CordFactory has been destroyed!
  542. // }
  543. // }
  544. ChunkRange Chunks() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  545. //----------------------------------------------------------------------------
  546. // Cord::CharIterator
  547. //----------------------------------------------------------------------------
  548. //
  549. // A `Cord::CharIterator` allows iteration over the constituent characters of
  550. // a `Cord`.
  551. //
  552. // Generally, you do not instantiate a `Cord::CharIterator` directly; instead,
  553. // you create one implicitly through use of the `Cord::Chars()` member
  554. // function.
  555. //
  556. // A `Cord::CharIterator` has the following properties:
  557. //
  558. // * The iterator is invalidated after any non-const operation on the
  559. // Cord object over which it iterates.
  560. // * Two `CharIterator` objects can be compared equal if and only if they
  561. // remain valid and iterate over the same Cord.
  562. // * The iterator keeps state that can grow for Cords that contain many
  563. // nodes and are imbalanced due to sharing. Prefer to pass this type by
  564. // const reference instead of by value.
  565. // * This type cannot act as a forward iterator because a `Cord` can reuse
  566. // sections of memory. This fact violates the requirement for forward
  567. // iterators to compare equal if dereferencing them returns the same
  568. // object.
  569. class CharIterator {
  570. public:
  571. using iterator_category = std::input_iterator_tag;
  572. using value_type = char;
  573. using difference_type = ptrdiff_t;
  574. using pointer = absl::Nonnull<const char*>;
  575. using reference = const char&;
  576. CharIterator() = default;
  577. CharIterator& operator++();
  578. CharIterator operator++(int);
  579. bool operator==(const CharIterator& other) const;
  580. bool operator!=(const CharIterator& other) const;
  581. reference operator*() const;
  582. friend Cord;
  583. private:
  584. explicit CharIterator(absl::Nonnull<const Cord*> cord)
  585. : chunk_iterator_(cord) {}
  586. ChunkIterator chunk_iterator_;
  587. };
  588. // Cord::AdvanceAndRead()
  589. //
  590. // Advances the `Cord::CharIterator` by `n_bytes` and returns the bytes
  591. // advanced as a separate `Cord`. `n_bytes` must be less than or equal to the
  592. // number of bytes within the Cord; otherwise, behavior is undefined. It is
  593. // valid to pass `char_end()` and `0`.
  594. static Cord AdvanceAndRead(absl::Nonnull<CharIterator*> it, size_t n_bytes);
  595. // Cord::Advance()
  596. //
  597. // Advances the `Cord::CharIterator` by `n_bytes`. `n_bytes` must be less than
  598. // or equal to the number of bytes remaining within the Cord; otherwise,
  599. // behavior is undefined. It is valid to pass `char_end()` and `0`.
  600. static void Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes);
  601. // Cord::ChunkRemaining()
  602. //
  603. // Returns the longest contiguous view starting at the iterator's position.
  604. //
  605. // `it` must be dereferenceable.
  606. static absl::string_view ChunkRemaining(const CharIterator& it);
  607. // Cord::char_begin()
  608. //
  609. // Returns an iterator to the first character of the `Cord`.
  610. //
  611. // Generally, prefer using `Cord::Chars()` within a range-based for loop for
  612. // iterating over the chunks of a Cord. This method may be useful for getting
  613. // a `CharIterator` where range-based for-loops may not be available.
  614. CharIterator char_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  615. // Cord::char_end()
  616. //
  617. // Returns an iterator to one past the last character of the `Cord`.
  618. //
  619. // Generally, prefer using `Cord::Chars()` within a range-based for loop for
  620. // iterating over the chunks of a Cord. This method may be useful for getting
  621. // a `CharIterator` where range-based for-loops are not useful.
  622. CharIterator char_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  623. // Cord::CharRange
  624. //
  625. // `CharRange` is a helper class for iterating over the characters of a
  626. // producing an iterator which can be used within a range-based for loop.
  627. // Construction of a `CharRange` will return an iterator pointing to the first
  628. // character of the Cord. Generally, do not construct a `CharRange` directly;
  629. // instead, prefer to use the `Cord::Chars()` method shown below.
  630. //
  631. // Implementation note: `CharRange` is simply a convenience wrapper over
  632. // `Cord::char_begin()` and `Cord::char_end()`.
  633. class CharRange {
  634. public:
  635. // Fulfill minimum c++ container requirements [container.requirements]
  636. // These (partial) container type definitions allow CharRange to be used
  637. // in various utilities expecting a subset of [container.requirements].
  638. // For example, the below enables using `::testing::ElementsAre(...)`
  639. using value_type = char;
  640. using reference = value_type&;
  641. using const_reference = const value_type&;
  642. using iterator = CharIterator;
  643. using const_iterator = CharIterator;
  644. explicit CharRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
  645. CharIterator begin() const;
  646. CharIterator end() const;
  647. private:
  648. absl::Nonnull<const Cord*> cord_;
  649. };
  650. // Cord::Chars()
  651. //
  652. // Returns a `Cord::CharRange` for iterating over the characters of a `Cord`
  653. // with a range-based for-loop. For most character-based iteration tasks on a
  654. // Cord, use `Cord::Chars()` to retrieve this iterator.
  655. //
  656. // Example:
  657. //
  658. // void ProcessCord(const Cord& cord) {
  659. // for (char c : cord.Chars()) { ... }
  660. // }
  661. //
  662. // Note that the ordinary caveats of temporary lifetime extension apply:
  663. //
  664. // void Process() {
  665. // for (char c : CordFactory().Chars()) {
  666. // // The temporary Cord returned by CordFactory has been destroyed!
  667. // }
  668. // }
  669. CharRange Chars() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  670. // Cord::operator[]
  671. //
  672. // Gets the "i"th character of the Cord and returns it, provided that
  673. // 0 <= i < Cord.size().
  674. //
  675. // NOTE: This routine is reasonably efficient. It is roughly
  676. // logarithmic based on the number of chunks that make up the cord. Still,
  677. // if you need to iterate over the contents of a cord, you should
  678. // use a CharIterator/ChunkIterator rather than call operator[] or Get()
  679. // repeatedly in a loop.
  680. char operator[](size_t i) const;
  681. // Cord::TryFlat()
  682. //
  683. // If this cord's representation is a single flat array, returns a
  684. // string_view referencing that array. Otherwise returns nullopt.
  685. absl::optional<absl::string_view> TryFlat() const
  686. ABSL_ATTRIBUTE_LIFETIME_BOUND;
  687. // Cord::Flatten()
  688. //
  689. // Flattens the cord into a single array and returns a view of the data.
  690. //
  691. // If the cord was already flat, the contents are not modified.
  692. absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND;
  693. // Cord::Find()
  694. //
  695. // Returns an iterator to the first occurrence of the substring `needle`.
  696. //
  697. // If the substring `needle` does not occur, `Cord::char_end()` is returned.
  698. CharIterator Find(absl::string_view needle) const;
  699. CharIterator Find(const absl::Cord& needle) const;
  700. // Supports absl::Cord as a sink object for absl::Format().
  701. friend void AbslFormatFlush(absl::Nonnull<absl::Cord*> cord,
  702. absl::string_view part) {
  703. cord->Append(part);
  704. }
  705. // Support automatic stringification with absl::StrCat and absl::StrFormat.
  706. template <typename Sink>
  707. friend void AbslStringify(Sink& sink, const absl::Cord& cord) {
  708. for (absl::string_view chunk : cord.Chunks()) {
  709. sink.Append(chunk);
  710. }
  711. }
  712. // Cord::SetExpectedChecksum()
  713. //
  714. // Stores a checksum value with this non-empty cord instance, for later
  715. // retrieval.
  716. //
  717. // The expected checksum is a number stored out-of-band, alongside the data.
  718. // It is preserved across copies and assignments, but any mutations to a cord
  719. // will cause it to lose its expected checksum.
  720. //
  721. // The expected checksum is not part of a Cord's value, and does not affect
  722. // operations such as equality or hashing.
  723. //
  724. // This field is intended to store a CRC32C checksum for later validation, to
  725. // help support end-to-end checksum workflows. However, the Cord API itself
  726. // does no CRC validation, and assigns no meaning to this number.
  727. //
  728. // This call has no effect if this cord is empty.
  729. void SetExpectedChecksum(uint32_t crc);
  730. // Returns this cord's expected checksum, if it has one. Otherwise, returns
  731. // nullopt.
  732. absl::optional<uint32_t> ExpectedChecksum() const;
  733. template <typename H>
  734. friend H AbslHashValue(H hash_state, const absl::Cord& c) {
  735. absl::optional<absl::string_view> maybe_flat = c.TryFlat();
  736. if (maybe_flat.has_value()) {
  737. return H::combine(std::move(hash_state), *maybe_flat);
  738. }
  739. return c.HashFragmented(std::move(hash_state));
  740. }
  741. // Create a Cord with the contents of StringConstant<T>::value.
  742. // No allocations will be done and no data will be copied.
  743. // This is an INTERNAL API and subject to change or removal. This API can only
  744. // be used by spelling absl::strings_internal::MakeStringConstant, which is
  745. // also an internal API.
  746. template <typename T>
  747. // NOLINTNEXTLINE(google-explicit-constructor)
  748. constexpr Cord(strings_internal::StringConstant<T>);
  749. private:
  750. using CordRep = absl::cord_internal::CordRep;
  751. using CordRepFlat = absl::cord_internal::CordRepFlat;
  752. using CordzInfo = cord_internal::CordzInfo;
  753. using CordzUpdateScope = cord_internal::CordzUpdateScope;
  754. using CordzUpdateTracker = cord_internal::CordzUpdateTracker;
  755. using InlineData = cord_internal::InlineData;
  756. using MethodIdentifier = CordzUpdateTracker::MethodIdentifier;
  757. // Creates a cord instance with `method` representing the originating
  758. // public API call causing the cord to be created.
  759. explicit Cord(absl::string_view src, MethodIdentifier method);
  760. friend class CordTestPeer;
  761. friend bool operator==(const Cord& lhs, const Cord& rhs);
  762. friend bool operator==(const Cord& lhs, absl::string_view rhs);
  763. #ifdef __cpp_impl_three_way_comparison
  764. // Cords support comparison with other Cords and string_views via operator<
  765. // and others; here we provide a wrapper for the C++20 three-way comparison
  766. // <=> operator.
  767. static inline std::strong_ordering ConvertCompareResultToStrongOrdering(
  768. int c) {
  769. if (c == 0) {
  770. return std::strong_ordering::equal;
  771. } else if (c < 0) {
  772. return std::strong_ordering::less;
  773. } else {
  774. return std::strong_ordering::greater;
  775. }
  776. }
  777. friend inline std::strong_ordering operator<=>(const Cord& x, const Cord& y) {
  778. return ConvertCompareResultToStrongOrdering(x.Compare(y));
  779. }
  780. friend inline std::strong_ordering operator<=>(const Cord& lhs,
  781. absl::string_view rhs) {
  782. return ConvertCompareResultToStrongOrdering(lhs.Compare(rhs));
  783. }
  784. friend inline std::strong_ordering operator<=>(absl::string_view lhs,
  785. const Cord& rhs) {
  786. return ConvertCompareResultToStrongOrdering(-rhs.Compare(lhs));
  787. }
  788. #endif
  789. friend absl::Nullable<const CordzInfo*> GetCordzInfoForTesting(
  790. const Cord& cord);
  791. // Calls the provided function once for each cord chunk, in order. Unlike
  792. // Chunks(), this API will not allocate memory.
  793. void ForEachChunk(absl::FunctionRef<void(absl::string_view)>) const;
  794. // Allocates new contiguous storage for the contents of the cord. This is
  795. // called by Flatten() when the cord was not already flat.
  796. absl::string_view FlattenSlowPath();
  797. // Actual cord contents are hidden inside the following simple
  798. // class so that we can isolate the bulk of cord.cc from changes
  799. // to the representation.
  800. //
  801. // InlineRep holds either a tree pointer, or an array of kMaxInline bytes.
  802. class InlineRep {
  803. public:
  804. static constexpr unsigned char kMaxInline = cord_internal::kMaxInline;
  805. static_assert(kMaxInline >= sizeof(absl::cord_internal::CordRep*), "");
  806. constexpr InlineRep() : data_() {}
  807. explicit InlineRep(InlineData::DefaultInitType init) : data_(init) {}
  808. InlineRep(const InlineRep& src);
  809. InlineRep(InlineRep&& src);
  810. InlineRep& operator=(const InlineRep& src);
  811. InlineRep& operator=(InlineRep&& src) noexcept;
  812. explicit constexpr InlineRep(absl::string_view sv,
  813. absl::Nullable<CordRep*> rep);
  814. void Swap(absl::Nonnull<InlineRep*> rhs);
  815. size_t size() const;
  816. // Returns nullptr if holding pointer
  817. absl::Nullable<const char*> data() const;
  818. // Discards pointer, if any
  819. void set_data(absl::Nonnull<const char*> data, size_t n);
  820. absl::Nonnull<char*> set_data(size_t n); // Write data to the result
  821. // Returns nullptr if holding bytes
  822. absl::Nullable<absl::cord_internal::CordRep*> tree() const;
  823. absl::Nonnull<absl::cord_internal::CordRep*> as_tree() const;
  824. absl::Nonnull<const char*> as_chars() const;
  825. // Returns non-null iff was holding a pointer
  826. absl::Nullable<absl::cord_internal::CordRep*> clear();
  827. // Converts to pointer if necessary.
  828. void reduce_size(size_t n); // REQUIRES: holding data
  829. void remove_prefix(size_t n); // REQUIRES: holding data
  830. void AppendArray(absl::string_view src, MethodIdentifier method);
  831. absl::string_view FindFlatStartPiece() const;
  832. // Creates a CordRepFlat instance from the current inlined data with `extra'
  833. // bytes of desired additional capacity.
  834. absl::Nonnull<CordRepFlat*> MakeFlatWithExtraCapacity(size_t extra);
  835. // Sets the tree value for this instance. `rep` must not be null.
  836. // Requires the current instance to hold a tree, and a lock to be held on
  837. // any CordzInfo referenced by this instance. The latter is enforced through
  838. // the CordzUpdateScope argument. If the current instance is sampled, then
  839. // the CordzInfo instance is updated to reference the new `rep` value.
  840. void SetTree(absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope);
  841. // Identical to SetTree(), except that `rep` is allowed to be null, in
  842. // which case the current instance is reset to an empty value.
  843. void SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
  844. const CordzUpdateScope& scope);
  845. // Sets the tree value for this instance, and randomly samples this cord.
  846. // This function disregards existing contents in `data_`, and should be
  847. // called when a Cord is 'promoted' from an 'uninitialized' or 'inlined'
  848. // value to a non-inlined (tree / ring) value.
  849. void EmplaceTree(absl::Nonnull<CordRep*> rep, MethodIdentifier method);
  850. // Identical to EmplaceTree, except that it copies the parent stack from
  851. // the provided `parent` data if the parent is sampled.
  852. void EmplaceTree(absl::Nonnull<CordRep*> rep, const InlineData& parent,
  853. MethodIdentifier method);
  854. // Commits the change of a newly created, or updated `rep` root value into
  855. // this cord. `old_rep` indicates the old (inlined or tree) value of the
  856. // cord, and determines if the commit invokes SetTree() or EmplaceTree().
  857. void CommitTree(absl::Nullable<const CordRep*> old_rep,
  858. absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope,
  859. MethodIdentifier method);
  860. void AppendTreeToInlined(absl::Nonnull<CordRep*> tree,
  861. MethodIdentifier method);
  862. void AppendTreeToTree(absl::Nonnull<CordRep*> tree,
  863. MethodIdentifier method);
  864. void AppendTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
  865. void PrependTreeToInlined(absl::Nonnull<CordRep*> tree,
  866. MethodIdentifier method);
  867. void PrependTreeToTree(absl::Nonnull<CordRep*> tree,
  868. MethodIdentifier method);
  869. void PrependTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
  870. bool IsSame(const InlineRep& other) const { return data_ == other.data_; }
  871. // Copies the inline contents into `dst`. Assumes the cord is not empty.
  872. void CopyTo(absl::Nonnull<std::string*> dst) const {
  873. data_.CopyInlineToString(dst);
  874. }
  875. // Copies the inline contents into `dst`. Assumes the cord is not empty.
  876. void CopyToArray(absl::Nonnull<char*> dst) const;
  877. bool is_tree() const { return data_.is_tree(); }
  878. // Returns true if the Cord is being profiled by cordz.
  879. bool is_profiled() const { return data_.is_tree() && data_.is_profiled(); }
  880. // Returns the available inlined capacity, or 0 if is_tree() == true.
  881. size_t remaining_inline_capacity() const {
  882. return data_.is_tree() ? 0 : kMaxInline - data_.inline_size();
  883. }
  884. // Returns the profiled CordzInfo, or nullptr if not sampled.
  885. absl::Nullable<absl::cord_internal::CordzInfo*> cordz_info() const {
  886. return data_.cordz_info();
  887. }
  888. // Sets the profiled CordzInfo.
  889. void set_cordz_info(absl::Nonnull<cord_internal::CordzInfo*> cordz_info) {
  890. assert(cordz_info != nullptr);
  891. data_.set_cordz_info(cordz_info);
  892. }
  893. // Resets the current cordz_info to null / empty.
  894. void clear_cordz_info() { data_.clear_cordz_info(); }
  895. private:
  896. friend class Cord;
  897. void AssignSlow(const InlineRep& src);
  898. // Unrefs the tree and stops profiling.
  899. void UnrefTree();
  900. void ResetToEmpty() { data_ = {}; }
  901. void set_inline_size(size_t size) { data_.set_inline_size(size); }
  902. size_t inline_size() const { return data_.inline_size(); }
  903. // Empty cords that carry a checksum have a CordRepCrc node with a null
  904. // child node. The code can avoid lots of special cases where it would
  905. // otherwise transition from tree to inline storage if we just remove the
  906. // CordRepCrc node before mutations. Must never be called inside a
  907. // CordzUpdateScope since it untracks the cordz info.
  908. void MaybeRemoveEmptyCrcNode();
  909. cord_internal::InlineData data_;
  910. };
  911. InlineRep contents_;
  912. // Helper for GetFlat() and TryFlat().
  913. static bool GetFlatAux(absl::Nonnull<absl::cord_internal::CordRep*> rep,
  914. absl::Nonnull<absl::string_view*> fragment);
  915. // Helper for ForEachChunk().
  916. static void ForEachChunkAux(
  917. absl::Nonnull<absl::cord_internal::CordRep*> rep,
  918. absl::FunctionRef<void(absl::string_view)> callback);
  919. // The destructor for non-empty Cords.
  920. void DestroyCordSlow();
  921. // Out-of-line implementation of slower parts of logic.
  922. void CopyToArraySlowPath(absl::Nonnull<char*> dst) const;
  923. int CompareSlowPath(absl::string_view rhs, size_t compared_size,
  924. size_t size_to_compare) const;
  925. int CompareSlowPath(const Cord& rhs, size_t compared_size,
  926. size_t size_to_compare) const;
  927. bool EqualsImpl(absl::string_view rhs, size_t size_to_compare) const;
  928. bool EqualsImpl(const Cord& rhs, size_t size_to_compare) const;
  929. int CompareImpl(const Cord& rhs) const;
  930. template <typename ResultType, typename RHS>
  931. friend ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
  932. size_t size_to_compare);
  933. static absl::string_view GetFirstChunk(const Cord& c);
  934. static absl::string_view GetFirstChunk(absl::string_view sv);
  935. // Returns a new reference to contents_.tree(), or steals an existing
  936. // reference if called on an rvalue.
  937. absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() const&;
  938. absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() &&;
  939. // Helper for Append().
  940. template <typename C>
  941. void AppendImpl(C&& src);
  942. // Appends / Prepends `src` to this instance, using precise sizing.
  943. // This method does explicitly not attempt to use any spare capacity
  944. // in any pending last added private owned flat.
  945. // Requires `src` to be <= kMaxFlatLength.
  946. void AppendPrecise(absl::string_view src, MethodIdentifier method);
  947. void PrependPrecise(absl::string_view src, MethodIdentifier method);
  948. CordBuffer GetAppendBufferSlowPath(size_t block_size, size_t capacity,
  949. size_t min_capacity);
  950. // Prepends the provided data to this instance. `method` contains the public
  951. // API method for this action which is tracked for Cordz sampling purposes.
  952. void PrependArray(absl::string_view src, MethodIdentifier method);
  953. // Assigns the value in 'src' to this instance, 'stealing' its contents.
  954. // Requires src.length() > kMaxBytesToCopy.
  955. Cord& AssignLargeString(std::string&& src);
  956. // Helper for AbslHashValue().
  957. template <typename H>
  958. H HashFragmented(H hash_state) const {
  959. typename H::AbslInternalPiecewiseCombiner combiner;
  960. ForEachChunk([&combiner, &hash_state](absl::string_view chunk) {
  961. hash_state = combiner.add_buffer(std::move(hash_state), chunk.data(),
  962. chunk.size());
  963. });
  964. return H::combine(combiner.finalize(std::move(hash_state)), size());
  965. }
  966. friend class CrcCord;
  967. void SetCrcCordState(crc_internal::CrcCordState state);
  968. absl::Nullable<const crc_internal::CrcCordState*> MaybeGetCrcCordState()
  969. const;
  970. CharIterator FindImpl(CharIterator it, absl::string_view needle) const;
  971. void CopyToArrayImpl(absl::Nonnull<char*> dst) const;
  972. };
  973. ABSL_NAMESPACE_END
  974. } // namespace absl
  975. namespace absl {
  976. ABSL_NAMESPACE_BEGIN
  977. // allow a Cord to be logged
  978. extern std::ostream& operator<<(std::ostream& out, const Cord& cord);
  979. // ------------------------------------------------------------------
  980. // Internal details follow. Clients should ignore.
  981. namespace cord_internal {
  982. // Does non-template-specific `CordRepExternal` initialization.
  983. // Requires `data` to be non-empty.
  984. void InitializeCordRepExternal(absl::string_view data,
  985. absl::Nonnull<CordRepExternal*> rep);
  986. // Creates a new `CordRep` that owns `data` and `releaser` and returns a pointer
  987. // to it. Requires `data` to be non-empty.
  988. template <typename Releaser>
  989. // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
  990. absl::Nonnull<CordRep*> NewExternalRep(absl::string_view data,
  991. Releaser&& releaser) {
  992. assert(!data.empty());
  993. using ReleaserType = absl::decay_t<Releaser>;
  994. CordRepExternal* rep = new CordRepExternalImpl<ReleaserType>(
  995. std::forward<Releaser>(releaser), 0);
  996. InitializeCordRepExternal(data, rep);
  997. return rep;
  998. }
  999. // Overload for function reference types that dispatches using a function
  1000. // pointer because there are no `alignof()` or `sizeof()` a function reference.
  1001. // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
  1002. inline absl::Nonnull<CordRep*> NewExternalRep(
  1003. absl::string_view data, void (&releaser)(absl::string_view)) {
  1004. return NewExternalRep(data, &releaser);
  1005. }
  1006. } // namespace cord_internal
  1007. template <typename Releaser>
  1008. Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser) {
  1009. Cord cord;
  1010. if (ABSL_PREDICT_TRUE(!data.empty())) {
  1011. cord.contents_.EmplaceTree(::absl::cord_internal::NewExternalRep(
  1012. data, std::forward<Releaser>(releaser)),
  1013. Cord::MethodIdentifier::kMakeCordFromExternal);
  1014. } else {
  1015. using ReleaserType = absl::decay_t<Releaser>;
  1016. cord_internal::InvokeReleaser(
  1017. cord_internal::Rank1{}, ReleaserType(std::forward<Releaser>(releaser)),
  1018. data);
  1019. }
  1020. return cord;
  1021. }
  1022. constexpr Cord::InlineRep::InlineRep(absl::string_view sv,
  1023. absl::Nullable<CordRep*> rep)
  1024. : data_(sv, rep) {}
  1025. inline Cord::InlineRep::InlineRep(const Cord::InlineRep& src)
  1026. : data_(InlineData::kDefaultInit) {
  1027. if (CordRep* tree = src.tree()) {
  1028. EmplaceTree(CordRep::Ref(tree), src.data_,
  1029. CordzUpdateTracker::kConstructorCord);
  1030. } else {
  1031. data_ = src.data_;
  1032. }
  1033. }
  1034. inline Cord::InlineRep::InlineRep(Cord::InlineRep&& src) : data_(src.data_) {
  1035. src.ResetToEmpty();
  1036. }
  1037. inline Cord::InlineRep& Cord::InlineRep::operator=(const Cord::InlineRep& src) {
  1038. if (this == &src) {
  1039. return *this;
  1040. }
  1041. if (!is_tree() && !src.is_tree()) {
  1042. data_ = src.data_;
  1043. return *this;
  1044. }
  1045. AssignSlow(src);
  1046. return *this;
  1047. }
  1048. inline Cord::InlineRep& Cord::InlineRep::operator=(
  1049. Cord::InlineRep&& src) noexcept {
  1050. if (is_tree()) {
  1051. UnrefTree();
  1052. }
  1053. data_ = src.data_;
  1054. src.ResetToEmpty();
  1055. return *this;
  1056. }
  1057. inline void Cord::InlineRep::Swap(absl::Nonnull<Cord::InlineRep*> rhs) {
  1058. if (rhs == this) {
  1059. return;
  1060. }
  1061. using std::swap;
  1062. swap(data_, rhs->data_);
  1063. }
  1064. inline absl::Nullable<const char*> Cord::InlineRep::data() const {
  1065. return is_tree() ? nullptr : data_.as_chars();
  1066. }
  1067. inline absl::Nonnull<const char*> Cord::InlineRep::as_chars() const {
  1068. assert(!data_.is_tree());
  1069. return data_.as_chars();
  1070. }
  1071. inline absl::Nonnull<absl::cord_internal::CordRep*> Cord::InlineRep::as_tree()
  1072. const {
  1073. assert(data_.is_tree());
  1074. return data_.as_tree();
  1075. }
  1076. inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::tree()
  1077. const {
  1078. if (is_tree()) {
  1079. return as_tree();
  1080. } else {
  1081. return nullptr;
  1082. }
  1083. }
  1084. inline size_t Cord::InlineRep::size() const {
  1085. return is_tree() ? as_tree()->length : inline_size();
  1086. }
  1087. inline absl::Nonnull<cord_internal::CordRepFlat*>
  1088. Cord::InlineRep::MakeFlatWithExtraCapacity(size_t extra) {
  1089. static_assert(cord_internal::kMinFlatLength >= sizeof(data_), "");
  1090. size_t len = data_.inline_size();
  1091. auto* result = CordRepFlat::New(len + extra);
  1092. result->length = len;
  1093. data_.copy_max_inline_to(result->Data());
  1094. return result;
  1095. }
  1096. inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
  1097. MethodIdentifier method) {
  1098. assert(rep);
  1099. data_.make_tree(rep);
  1100. CordzInfo::MaybeTrackCord(data_, method);
  1101. }
  1102. inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
  1103. const InlineData& parent,
  1104. MethodIdentifier method) {
  1105. data_.make_tree(rep);
  1106. CordzInfo::MaybeTrackCord(data_, parent, method);
  1107. }
  1108. inline void Cord::InlineRep::SetTree(absl::Nonnull<CordRep*> rep,
  1109. const CordzUpdateScope& scope) {
  1110. assert(rep);
  1111. assert(data_.is_tree());
  1112. data_.set_tree(rep);
  1113. scope.SetCordRep(rep);
  1114. }
  1115. inline void Cord::InlineRep::SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
  1116. const CordzUpdateScope& scope) {
  1117. assert(data_.is_tree());
  1118. if (rep) {
  1119. data_.set_tree(rep);
  1120. } else {
  1121. data_ = {};
  1122. }
  1123. scope.SetCordRep(rep);
  1124. }
  1125. inline void Cord::InlineRep::CommitTree(absl::Nullable<const CordRep*> old_rep,
  1126. absl::Nonnull<CordRep*> rep,
  1127. const CordzUpdateScope& scope,
  1128. MethodIdentifier method) {
  1129. if (old_rep) {
  1130. SetTree(rep, scope);
  1131. } else {
  1132. EmplaceTree(rep, method);
  1133. }
  1134. }
  1135. inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::clear() {
  1136. if (is_tree()) {
  1137. CordzInfo::MaybeUntrackCord(cordz_info());
  1138. }
  1139. absl::cord_internal::CordRep* result = tree();
  1140. ResetToEmpty();
  1141. return result;
  1142. }
  1143. inline void Cord::InlineRep::CopyToArray(absl::Nonnull<char*> dst) const {
  1144. assert(!is_tree());
  1145. size_t n = inline_size();
  1146. assert(n != 0);
  1147. cord_internal::SmallMemmove(dst, data_.as_chars(), n);
  1148. }
  1149. inline void Cord::InlineRep::MaybeRemoveEmptyCrcNode() {
  1150. CordRep* rep = tree();
  1151. if (rep == nullptr || ABSL_PREDICT_TRUE(rep->length > 0)) {
  1152. return;
  1153. }
  1154. assert(rep->IsCrc());
  1155. assert(rep->crc()->child == nullptr);
  1156. CordzInfo::MaybeUntrackCord(cordz_info());
  1157. CordRep::Unref(rep);
  1158. ResetToEmpty();
  1159. }
  1160. constexpr inline Cord::Cord() noexcept {}
  1161. inline Cord::Cord(absl::string_view src)
  1162. : Cord(src, CordzUpdateTracker::kConstructorString) {}
  1163. template <typename T>
  1164. constexpr Cord::Cord(strings_internal::StringConstant<T>)
  1165. : contents_(strings_internal::StringConstant<T>::value,
  1166. strings_internal::StringConstant<T>::value.size() <=
  1167. cord_internal::kMaxInline
  1168. ? nullptr
  1169. : &cord_internal::ConstInitExternalStorage<
  1170. strings_internal::StringConstant<T>>::value) {}
  1171. inline Cord& Cord::operator=(const Cord& x) {
  1172. contents_ = x.contents_;
  1173. return *this;
  1174. }
  1175. template <typename T, Cord::EnableIfString<T>>
  1176. Cord& Cord::operator=(T&& src) {
  1177. if (src.size() <= cord_internal::kMaxBytesToCopy) {
  1178. return operator=(absl::string_view(src));
  1179. } else {
  1180. return AssignLargeString(std::forward<T>(src));
  1181. }
  1182. }
  1183. inline Cord::Cord(const Cord& src) : contents_(src.contents_) {}
  1184. inline Cord::Cord(Cord&& src) noexcept : contents_(std::move(src.contents_)) {}
  1185. inline void Cord::swap(Cord& other) noexcept {
  1186. contents_.Swap(&other.contents_);
  1187. }
  1188. inline Cord& Cord::operator=(Cord&& x) noexcept {
  1189. contents_ = std::move(x.contents_);
  1190. return *this;
  1191. }
  1192. extern template Cord::Cord(std::string&& src);
  1193. inline size_t Cord::size() const {
  1194. // Length is 1st field in str.rep_
  1195. return contents_.size();
  1196. }
  1197. inline bool Cord::empty() const { return size() == 0; }
  1198. inline size_t Cord::EstimatedMemoryUsage(
  1199. CordMemoryAccounting accounting_method) const {
  1200. size_t result = sizeof(Cord);
  1201. if (const absl::cord_internal::CordRep* rep = contents_.tree()) {
  1202. switch (accounting_method) {
  1203. case CordMemoryAccounting::kFairShare:
  1204. result += cord_internal::GetEstimatedFairShareMemoryUsage(rep);
  1205. break;
  1206. case CordMemoryAccounting::kTotalMorePrecise:
  1207. result += cord_internal::GetMorePreciseMemoryUsage(rep);
  1208. break;
  1209. case CordMemoryAccounting::kTotal:
  1210. result += cord_internal::GetEstimatedMemoryUsage(rep);
  1211. break;
  1212. }
  1213. }
  1214. return result;
  1215. }
  1216. inline absl::optional<absl::string_view> Cord::TryFlat() const
  1217. ABSL_ATTRIBUTE_LIFETIME_BOUND {
  1218. absl::cord_internal::CordRep* rep = contents_.tree();
  1219. if (rep == nullptr) {
  1220. return absl::string_view(contents_.data(), contents_.size());
  1221. }
  1222. absl::string_view fragment;
  1223. if (GetFlatAux(rep, &fragment)) {
  1224. return fragment;
  1225. }
  1226. return absl::nullopt;
  1227. }
  1228. inline absl::string_view Cord::Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND {
  1229. absl::cord_internal::CordRep* rep = contents_.tree();
  1230. if (rep == nullptr) {
  1231. return absl::string_view(contents_.data(), contents_.size());
  1232. } else {
  1233. absl::string_view already_flat_contents;
  1234. if (GetFlatAux(rep, &already_flat_contents)) {
  1235. return already_flat_contents;
  1236. }
  1237. }
  1238. return FlattenSlowPath();
  1239. }
  1240. inline void Cord::Append(absl::string_view src) {
  1241. contents_.AppendArray(src, CordzUpdateTracker::kAppendString);
  1242. }
  1243. inline void Cord::Prepend(absl::string_view src) {
  1244. PrependArray(src, CordzUpdateTracker::kPrependString);
  1245. }
  1246. inline void Cord::Append(CordBuffer buffer) {
  1247. if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
  1248. contents_.MaybeRemoveEmptyCrcNode();
  1249. absl::string_view short_value;
  1250. if (CordRep* rep = buffer.ConsumeValue(short_value)) {
  1251. contents_.AppendTree(rep, CordzUpdateTracker::kAppendCordBuffer);
  1252. } else {
  1253. AppendPrecise(short_value, CordzUpdateTracker::kAppendCordBuffer);
  1254. }
  1255. }
  1256. inline void Cord::Prepend(CordBuffer buffer) {
  1257. if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
  1258. contents_.MaybeRemoveEmptyCrcNode();
  1259. absl::string_view short_value;
  1260. if (CordRep* rep = buffer.ConsumeValue(short_value)) {
  1261. contents_.PrependTree(rep, CordzUpdateTracker::kPrependCordBuffer);
  1262. } else {
  1263. PrependPrecise(short_value, CordzUpdateTracker::kPrependCordBuffer);
  1264. }
  1265. }
  1266. inline CordBuffer Cord::GetAppendBuffer(size_t capacity, size_t min_capacity) {
  1267. if (empty()) return CordBuffer::CreateWithDefaultLimit(capacity);
  1268. return GetAppendBufferSlowPath(0, capacity, min_capacity);
  1269. }
  1270. inline CordBuffer Cord::GetCustomAppendBuffer(size_t block_size,
  1271. size_t capacity,
  1272. size_t min_capacity) {
  1273. if (empty()) {
  1274. return block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity)
  1275. : CordBuffer::CreateWithDefaultLimit(capacity);
  1276. }
  1277. return GetAppendBufferSlowPath(block_size, capacity, min_capacity);
  1278. }
  1279. extern template void Cord::Append(std::string&& src);
  1280. extern template void Cord::Prepend(std::string&& src);
  1281. inline int Cord::Compare(const Cord& rhs) const {
  1282. if (!contents_.is_tree() && !rhs.contents_.is_tree()) {
  1283. return contents_.data_.Compare(rhs.contents_.data_);
  1284. }
  1285. return CompareImpl(rhs);
  1286. }
  1287. // Does 'this' cord start/end with rhs
  1288. inline bool Cord::StartsWith(const Cord& rhs) const {
  1289. if (contents_.IsSame(rhs.contents_)) return true;
  1290. size_t rhs_size = rhs.size();
  1291. if (size() < rhs_size) return false;
  1292. return EqualsImpl(rhs, rhs_size);
  1293. }
  1294. inline bool Cord::StartsWith(absl::string_view rhs) const {
  1295. size_t rhs_size = rhs.size();
  1296. if (size() < rhs_size) return false;
  1297. return EqualsImpl(rhs, rhs_size);
  1298. }
  1299. inline void Cord::CopyToArrayImpl(absl::Nonnull<char*> dst) const {
  1300. if (!contents_.is_tree()) {
  1301. if (!empty()) contents_.CopyToArray(dst);
  1302. } else {
  1303. CopyToArraySlowPath(dst);
  1304. }
  1305. }
  1306. inline void Cord::ChunkIterator::InitTree(
  1307. absl::Nonnull<cord_internal::CordRep*> tree) {
  1308. tree = cord_internal::SkipCrcNode(tree);
  1309. if (tree->tag == cord_internal::BTREE) {
  1310. current_chunk_ = btree_reader_.Init(tree->btree());
  1311. } else {
  1312. current_leaf_ = tree;
  1313. current_chunk_ = cord_internal::EdgeData(tree);
  1314. }
  1315. }
  1316. inline Cord::ChunkIterator::ChunkIterator(
  1317. absl::Nonnull<cord_internal::CordRep*> tree) {
  1318. bytes_remaining_ = tree->length;
  1319. InitTree(tree);
  1320. }
  1321. inline Cord::ChunkIterator::ChunkIterator(absl::Nonnull<const Cord*> cord) {
  1322. if (CordRep* tree = cord->contents_.tree()) {
  1323. bytes_remaining_ = tree->length;
  1324. if (ABSL_PREDICT_TRUE(bytes_remaining_ != 0)) {
  1325. InitTree(tree);
  1326. } else {
  1327. current_chunk_ = {};
  1328. }
  1329. } else {
  1330. bytes_remaining_ = cord->contents_.inline_size();
  1331. current_chunk_ = {cord->contents_.data(), bytes_remaining_};
  1332. }
  1333. }
  1334. inline Cord::ChunkIterator& Cord::ChunkIterator::AdvanceBtree() {
  1335. current_chunk_ = btree_reader_.Next();
  1336. return *this;
  1337. }
  1338. inline void Cord::ChunkIterator::AdvanceBytesBtree(size_t n) {
  1339. assert(n >= current_chunk_.size());
  1340. bytes_remaining_ -= n;
  1341. if (bytes_remaining_) {
  1342. if (n == current_chunk_.size()) {
  1343. current_chunk_ = btree_reader_.Next();
  1344. } else {
  1345. size_t offset = btree_reader_.length() - bytes_remaining_;
  1346. current_chunk_ = btree_reader_.Seek(offset);
  1347. }
  1348. } else {
  1349. current_chunk_ = {};
  1350. }
  1351. }
  1352. inline Cord::ChunkIterator& Cord::ChunkIterator::operator++() {
  1353. ABSL_HARDENING_ASSERT(bytes_remaining_ > 0 &&
  1354. "Attempted to iterate past `end()`");
  1355. assert(bytes_remaining_ >= current_chunk_.size());
  1356. bytes_remaining_ -= current_chunk_.size();
  1357. if (bytes_remaining_ > 0) {
  1358. if (btree_reader_) {
  1359. return AdvanceBtree();
  1360. } else {
  1361. assert(!current_chunk_.empty()); // Called on invalid iterator.
  1362. }
  1363. current_chunk_ = {};
  1364. }
  1365. return *this;
  1366. }
  1367. inline Cord::ChunkIterator Cord::ChunkIterator::operator++(int) {
  1368. ChunkIterator tmp(*this);
  1369. operator++();
  1370. return tmp;
  1371. }
  1372. inline bool Cord::ChunkIterator::operator==(const ChunkIterator& other) const {
  1373. return bytes_remaining_ == other.bytes_remaining_;
  1374. }
  1375. inline bool Cord::ChunkIterator::operator!=(const ChunkIterator& other) const {
  1376. return !(*this == other);
  1377. }
  1378. inline Cord::ChunkIterator::reference Cord::ChunkIterator::operator*() const {
  1379. ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
  1380. return current_chunk_;
  1381. }
  1382. inline Cord::ChunkIterator::pointer Cord::ChunkIterator::operator->() const {
  1383. ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
  1384. return &current_chunk_;
  1385. }
  1386. inline void Cord::ChunkIterator::RemoveChunkPrefix(size_t n) {
  1387. assert(n < current_chunk_.size());
  1388. current_chunk_.remove_prefix(n);
  1389. bytes_remaining_ -= n;
  1390. }
  1391. inline void Cord::ChunkIterator::AdvanceBytes(size_t n) {
  1392. assert(bytes_remaining_ >= n);
  1393. if (ABSL_PREDICT_TRUE(n < current_chunk_.size())) {
  1394. RemoveChunkPrefix(n);
  1395. } else if (n != 0) {
  1396. if (btree_reader_) {
  1397. AdvanceBytesBtree(n);
  1398. } else {
  1399. bytes_remaining_ = 0;
  1400. }
  1401. }
  1402. }
  1403. inline Cord::ChunkIterator Cord::chunk_begin() const {
  1404. return ChunkIterator(this);
  1405. }
  1406. inline Cord::ChunkIterator Cord::chunk_end() const { return ChunkIterator(); }
  1407. inline Cord::ChunkIterator Cord::ChunkRange::begin() const {
  1408. return cord_->chunk_begin();
  1409. }
  1410. inline Cord::ChunkIterator Cord::ChunkRange::end() const {
  1411. return cord_->chunk_end();
  1412. }
  1413. inline Cord::ChunkRange Cord::Chunks() const { return ChunkRange(this); }
  1414. inline Cord::CharIterator& Cord::CharIterator::operator++() {
  1415. if (ABSL_PREDICT_TRUE(chunk_iterator_->size() > 1)) {
  1416. chunk_iterator_.RemoveChunkPrefix(1);
  1417. } else {
  1418. ++chunk_iterator_;
  1419. }
  1420. return *this;
  1421. }
  1422. inline Cord::CharIterator Cord::CharIterator::operator++(int) {
  1423. CharIterator tmp(*this);
  1424. operator++();
  1425. return tmp;
  1426. }
  1427. inline bool Cord::CharIterator::operator==(const CharIterator& other) const {
  1428. return chunk_iterator_ == other.chunk_iterator_;
  1429. }
  1430. inline bool Cord::CharIterator::operator!=(const CharIterator& other) const {
  1431. return !(*this == other);
  1432. }
  1433. inline Cord::CharIterator::reference Cord::CharIterator::operator*() const {
  1434. return *chunk_iterator_->data();
  1435. }
  1436. inline Cord Cord::AdvanceAndRead(absl::Nonnull<CharIterator*> it,
  1437. size_t n_bytes) {
  1438. assert(it != nullptr);
  1439. return it->chunk_iterator_.AdvanceAndReadBytes(n_bytes);
  1440. }
  1441. inline void Cord::Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes) {
  1442. assert(it != nullptr);
  1443. it->chunk_iterator_.AdvanceBytes(n_bytes);
  1444. }
  1445. inline absl::string_view Cord::ChunkRemaining(const CharIterator& it) {
  1446. return *it.chunk_iterator_;
  1447. }
  1448. inline Cord::CharIterator Cord::char_begin() const {
  1449. return CharIterator(this);
  1450. }
  1451. inline Cord::CharIterator Cord::char_end() const { return CharIterator(); }
  1452. inline Cord::CharIterator Cord::CharRange::begin() const {
  1453. return cord_->char_begin();
  1454. }
  1455. inline Cord::CharIterator Cord::CharRange::end() const {
  1456. return cord_->char_end();
  1457. }
  1458. inline Cord::CharRange Cord::Chars() const { return CharRange(this); }
  1459. inline void Cord::ForEachChunk(
  1460. absl::FunctionRef<void(absl::string_view)> callback) const {
  1461. absl::cord_internal::CordRep* rep = contents_.tree();
  1462. if (rep == nullptr) {
  1463. callback(absl::string_view(contents_.data(), contents_.size()));
  1464. } else {
  1465. ForEachChunkAux(rep, callback);
  1466. }
  1467. }
  1468. // Nonmember Cord-to-Cord relational operators.
  1469. inline bool operator==(const Cord& lhs, const Cord& rhs) {
  1470. if (lhs.contents_.IsSame(rhs.contents_)) return true;
  1471. size_t rhs_size = rhs.size();
  1472. if (lhs.size() != rhs_size) return false;
  1473. return lhs.EqualsImpl(rhs, rhs_size);
  1474. }
  1475. inline bool operator!=(const Cord& x, const Cord& y) { return !(x == y); }
  1476. inline bool operator<(const Cord& x, const Cord& y) { return x.Compare(y) < 0; }
  1477. inline bool operator>(const Cord& x, const Cord& y) { return x.Compare(y) > 0; }
  1478. inline bool operator<=(const Cord& x, const Cord& y) {
  1479. return x.Compare(y) <= 0;
  1480. }
  1481. inline bool operator>=(const Cord& x, const Cord& y) {
  1482. return x.Compare(y) >= 0;
  1483. }
  1484. // Nonmember Cord-to-absl::string_view relational operators.
  1485. //
  1486. // Due to implicit conversions, these also enable comparisons of Cord with
  1487. // std::string and const char*.
  1488. inline bool operator==(const Cord& lhs, absl::string_view rhs) {
  1489. size_t lhs_size = lhs.size();
  1490. size_t rhs_size = rhs.size();
  1491. if (lhs_size != rhs_size) return false;
  1492. return lhs.EqualsImpl(rhs, rhs_size);
  1493. }
  1494. inline bool operator==(absl::string_view x, const Cord& y) { return y == x; }
  1495. inline bool operator!=(const Cord& x, absl::string_view y) { return !(x == y); }
  1496. inline bool operator!=(absl::string_view x, const Cord& y) { return !(x == y); }
  1497. inline bool operator<(const Cord& x, absl::string_view y) {
  1498. return x.Compare(y) < 0;
  1499. }
  1500. inline bool operator<(absl::string_view x, const Cord& y) {
  1501. return y.Compare(x) > 0;
  1502. }
  1503. inline bool operator>(const Cord& x, absl::string_view y) { return y < x; }
  1504. inline bool operator>(absl::string_view x, const Cord& y) { return y < x; }
  1505. inline bool operator<=(const Cord& x, absl::string_view y) { return !(y < x); }
  1506. inline bool operator<=(absl::string_view x, const Cord& y) { return !(y < x); }
  1507. inline bool operator>=(const Cord& x, absl::string_view y) { return !(x < y); }
  1508. inline bool operator>=(absl::string_view x, const Cord& y) { return !(x < y); }
  1509. // Some internals exposed to test code.
  1510. namespace strings_internal {
  1511. class CordTestAccess {
  1512. public:
  1513. static size_t FlatOverhead();
  1514. static size_t MaxFlatLength();
  1515. static size_t SizeofCordRepExternal();
  1516. static size_t SizeofCordRepSubstring();
  1517. static size_t FlatTagToLength(uint8_t tag);
  1518. static uint8_t LengthToTag(size_t s);
  1519. };
  1520. } // namespace strings_internal
  1521. ABSL_NAMESPACE_END
  1522. } // namespace absl
  1523. #endif // ABSL_STRINGS_CORD_H_