cord.h 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  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 <cstddef>
  63. #include <cstdint>
  64. #include <cstring>
  65. #include <iosfwd>
  66. #include <iterator>
  67. #include <string>
  68. #include <type_traits>
  69. #include "absl/base/attributes.h"
  70. #include "absl/base/config.h"
  71. #include "absl/base/internal/endian.h"
  72. #include "absl/base/internal/per_thread_tls.h"
  73. #include "absl/base/macros.h"
  74. #include "absl/base/nullability.h"
  75. #include "absl/base/port.h"
  76. #include "absl/container/inlined_vector.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/cordz_functions.h"
  88. #include "absl/strings/internal/cordz_info.h"
  89. #include "absl/strings/internal/cordz_statistics.h"
  90. #include "absl/strings/internal/cordz_update_scope.h"
  91. #include "absl/strings/internal/cordz_update_tracker.h"
  92. #include "absl/strings/internal/resize_uninitialized.h"
  93. #include "absl/strings/internal/string_constant.h"
  94. #include "absl/strings/string_view.h"
  95. #include "absl/types/optional.h"
  96. namespace absl {
  97. ABSL_NAMESPACE_BEGIN
  98. class Cord;
  99. class CordTestPeer;
  100. template <typename Releaser>
  101. Cord MakeCordFromExternal(absl::string_view, Releaser&&);
  102. void CopyCordToString(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. class CharIterator;
  388. //----------------------------------------------------------------------------
  389. // Cord::ChunkIterator
  390. //----------------------------------------------------------------------------
  391. //
  392. // A `Cord::ChunkIterator` allows iteration over the constituent chunks of its
  393. // Cord. Such iteration allows you to perform non-const operations on the data
  394. // of a Cord without modifying it.
  395. //
  396. // Generally, you do not instantiate a `Cord::ChunkIterator` directly;
  397. // instead, you create one implicitly through use of the `Cord::Chunks()`
  398. // member function.
  399. //
  400. // The `Cord::ChunkIterator` has the following properties:
  401. //
  402. // * The iterator is invalidated after any non-const operation on the
  403. // Cord object over which it iterates.
  404. // * The `string_view` returned by dereferencing a valid, non-`end()`
  405. // iterator is guaranteed to be non-empty.
  406. // * Two `ChunkIterator` objects can be compared equal if and only if they
  407. // remain valid and iterate over the same Cord.
  408. // * The iterator in this case is a proxy iterator; the `string_view`
  409. // returned by the iterator does not live inside the Cord, and its
  410. // lifetime is limited to the lifetime of the iterator itself. To help
  411. // prevent lifetime issues, `ChunkIterator::reference` is not a true
  412. // reference type and is equivalent to `value_type`.
  413. // * The iterator keeps state that can grow for Cords that contain many
  414. // nodes and are imbalanced due to sharing. Prefer to pass this type by
  415. // const reference instead of by value.
  416. class ChunkIterator {
  417. public:
  418. using iterator_category = std::input_iterator_tag;
  419. using value_type = absl::string_view;
  420. using difference_type = ptrdiff_t;
  421. using pointer = absl::Nonnull<const value_type*>;
  422. using reference = value_type;
  423. ChunkIterator() = default;
  424. ChunkIterator& operator++();
  425. ChunkIterator operator++(int);
  426. bool operator==(const ChunkIterator& other) const;
  427. bool operator!=(const ChunkIterator& other) const;
  428. reference operator*() const;
  429. pointer operator->() const;
  430. friend class Cord;
  431. friend class CharIterator;
  432. private:
  433. using CordRep = absl::cord_internal::CordRep;
  434. using CordRepBtree = absl::cord_internal::CordRepBtree;
  435. using CordRepBtreeReader = absl::cord_internal::CordRepBtreeReader;
  436. // Constructs a `begin()` iterator from `tree`.
  437. explicit ChunkIterator(absl::Nonnull<cord_internal::CordRep*> tree);
  438. // Constructs a `begin()` iterator from `cord`.
  439. explicit ChunkIterator(absl::Nonnull<const Cord*> cord);
  440. // Initializes this instance from a tree. Invoked by constructors.
  441. void InitTree(absl::Nonnull<cord_internal::CordRep*> tree);
  442. // Removes `n` bytes from `current_chunk_`. Expects `n` to be smaller than
  443. // `current_chunk_.size()`.
  444. void RemoveChunkPrefix(size_t n);
  445. Cord AdvanceAndReadBytes(size_t n);
  446. void AdvanceBytes(size_t n);
  447. // Btree specific operator++
  448. ChunkIterator& AdvanceBtree();
  449. void AdvanceBytesBtree(size_t n);
  450. // A view into bytes of the current `CordRep`. It may only be a view to a
  451. // suffix of bytes if this is being used by `CharIterator`.
  452. absl::string_view current_chunk_;
  453. // The current leaf, or `nullptr` if the iterator points to short data.
  454. // If the current chunk is a substring node, current_leaf_ points to the
  455. // underlying flat or external node.
  456. absl::Nullable<absl::cord_internal::CordRep*> current_leaf_ = nullptr;
  457. // The number of bytes left in the `Cord` over which we are iterating.
  458. size_t bytes_remaining_ = 0;
  459. // Cord reader for cord btrees. Empty if not traversing a btree.
  460. CordRepBtreeReader btree_reader_;
  461. };
  462. // Cord::chunk_begin()
  463. //
  464. // Returns an iterator to the first chunk of the `Cord`.
  465. //
  466. // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
  467. // iterating over the chunks of a Cord. This method may be useful for getting
  468. // a `ChunkIterator` where range-based for-loops are not useful.
  469. //
  470. // Example:
  471. //
  472. // absl::Cord::ChunkIterator FindAsChunk(const absl::Cord& c,
  473. // absl::string_view s) {
  474. // return std::find(c.chunk_begin(), c.chunk_end(), s);
  475. // }
  476. ChunkIterator chunk_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  477. // Cord::chunk_end()
  478. //
  479. // Returns an iterator one increment past the last chunk of the `Cord`.
  480. //
  481. // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
  482. // iterating over the chunks of a Cord. This method may be useful for getting
  483. // a `ChunkIterator` where range-based for-loops may not be available.
  484. ChunkIterator chunk_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  485. //----------------------------------------------------------------------------
  486. // Cord::ChunkRange
  487. //----------------------------------------------------------------------------
  488. //
  489. // `ChunkRange` is a helper class for iterating over the chunks of the `Cord`,
  490. // producing an iterator which can be used within a range-based for loop.
  491. // Construction of a `ChunkRange` will return an iterator pointing to the
  492. // first chunk of the Cord. Generally, do not construct a `ChunkRange`
  493. // directly; instead, prefer to use the `Cord::Chunks()` method.
  494. //
  495. // Implementation note: `ChunkRange` is simply a convenience wrapper over
  496. // `Cord::chunk_begin()` and `Cord::chunk_end()`.
  497. class ChunkRange {
  498. public:
  499. // Fulfill minimum c++ container requirements [container.requirements]
  500. // These (partial) container type definitions allow ChunkRange to be used
  501. // in various utilities expecting a subset of [container.requirements].
  502. // For example, the below enables using `::testing::ElementsAre(...)`
  503. using value_type = absl::string_view;
  504. using reference = value_type&;
  505. using const_reference = const value_type&;
  506. using iterator = ChunkIterator;
  507. using const_iterator = ChunkIterator;
  508. explicit ChunkRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
  509. ChunkIterator begin() const;
  510. ChunkIterator end() const;
  511. private:
  512. absl::Nonnull<const Cord*> cord_;
  513. };
  514. // Cord::Chunks()
  515. //
  516. // Returns a `Cord::ChunkRange` for iterating over the chunks of a `Cord` with
  517. // a range-based for-loop. For most iteration tasks on a Cord, use
  518. // `Cord::Chunks()` to retrieve this iterator.
  519. //
  520. // Example:
  521. //
  522. // void ProcessChunks(const Cord& cord) {
  523. // for (absl::string_view chunk : cord.Chunks()) { ... }
  524. // }
  525. //
  526. // Note that the ordinary caveats of temporary lifetime extension apply:
  527. //
  528. // void Process() {
  529. // for (absl::string_view chunk : CordFactory().Chunks()) {
  530. // // The temporary Cord returned by CordFactory has been destroyed!
  531. // }
  532. // }
  533. ChunkRange Chunks() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  534. //----------------------------------------------------------------------------
  535. // Cord::CharIterator
  536. //----------------------------------------------------------------------------
  537. //
  538. // A `Cord::CharIterator` allows iteration over the constituent characters of
  539. // a `Cord`.
  540. //
  541. // Generally, you do not instantiate a `Cord::CharIterator` directly; instead,
  542. // you create one implicitly through use of the `Cord::Chars()` member
  543. // function.
  544. //
  545. // A `Cord::CharIterator` has the following properties:
  546. //
  547. // * The iterator is invalidated after any non-const operation on the
  548. // Cord object over which it iterates.
  549. // * Two `CharIterator` objects can be compared equal if and only if they
  550. // remain valid and iterate over the same Cord.
  551. // * The iterator keeps state that can grow for Cords that contain many
  552. // nodes and are imbalanced due to sharing. Prefer to pass this type by
  553. // const reference instead of by value.
  554. // * This type cannot act as a forward iterator because a `Cord` can reuse
  555. // sections of memory. This fact violates the requirement for forward
  556. // iterators to compare equal if dereferencing them returns the same
  557. // object.
  558. class CharIterator {
  559. public:
  560. using iterator_category = std::input_iterator_tag;
  561. using value_type = char;
  562. using difference_type = ptrdiff_t;
  563. using pointer = absl::Nonnull<const char*>;
  564. using reference = const char&;
  565. CharIterator() = default;
  566. CharIterator& operator++();
  567. CharIterator operator++(int);
  568. bool operator==(const CharIterator& other) const;
  569. bool operator!=(const CharIterator& other) const;
  570. reference operator*() const;
  571. pointer operator->() const;
  572. friend Cord;
  573. private:
  574. explicit CharIterator(absl::Nonnull<const Cord*> cord)
  575. : chunk_iterator_(cord) {}
  576. ChunkIterator chunk_iterator_;
  577. };
  578. // Cord::AdvanceAndRead()
  579. //
  580. // Advances the `Cord::CharIterator` by `n_bytes` and returns the bytes
  581. // advanced as a separate `Cord`. `n_bytes` must be less than or equal to the
  582. // number of bytes within the Cord; otherwise, behavior is undefined. It is
  583. // valid to pass `char_end()` and `0`.
  584. static Cord AdvanceAndRead(absl::Nonnull<CharIterator*> it, size_t n_bytes);
  585. // Cord::Advance()
  586. //
  587. // Advances the `Cord::CharIterator` by `n_bytes`. `n_bytes` must be less than
  588. // or equal to the number of bytes remaining within the Cord; otherwise,
  589. // behavior is undefined. It is valid to pass `char_end()` and `0`.
  590. static void Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes);
  591. // Cord::ChunkRemaining()
  592. //
  593. // Returns the longest contiguous view starting at the iterator's position.
  594. //
  595. // `it` must be dereferenceable.
  596. static absl::string_view ChunkRemaining(const CharIterator& it);
  597. // Cord::char_begin()
  598. //
  599. // Returns an iterator to the first character of the `Cord`.
  600. //
  601. // Generally, prefer using `Cord::Chars()` within a range-based for loop for
  602. // iterating over the chunks of a Cord. This method may be useful for getting
  603. // a `CharIterator` where range-based for-loops may not be available.
  604. CharIterator char_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  605. // Cord::char_end()
  606. //
  607. // Returns an iterator to one past the last character of the `Cord`.
  608. //
  609. // Generally, prefer using `Cord::Chars()` within a range-based for loop for
  610. // iterating over the chunks of a Cord. This method may be useful for getting
  611. // a `CharIterator` where range-based for-loops are not useful.
  612. CharIterator char_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  613. // Cord::CharRange
  614. //
  615. // `CharRange` is a helper class for iterating over the characters of a
  616. // producing an iterator which can be used within a range-based for loop.
  617. // Construction of a `CharRange` will return an iterator pointing to the first
  618. // character of the Cord. Generally, do not construct a `CharRange` directly;
  619. // instead, prefer to use the `Cord::Chars()` method shown below.
  620. //
  621. // Implementation note: `CharRange` is simply a convenience wrapper over
  622. // `Cord::char_begin()` and `Cord::char_end()`.
  623. class CharRange {
  624. public:
  625. // Fulfill minimum c++ container requirements [container.requirements]
  626. // These (partial) container type definitions allow CharRange to be used
  627. // in various utilities expecting a subset of [container.requirements].
  628. // For example, the below enables using `::testing::ElementsAre(...)`
  629. using value_type = char;
  630. using reference = value_type&;
  631. using const_reference = const value_type&;
  632. using iterator = CharIterator;
  633. using const_iterator = CharIterator;
  634. explicit CharRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
  635. CharIterator begin() const;
  636. CharIterator end() const;
  637. private:
  638. absl::Nonnull<const Cord*> cord_;
  639. };
  640. // Cord::Chars()
  641. //
  642. // Returns a `Cord::CharRange` for iterating over the characters of a `Cord`
  643. // with a range-based for-loop. For most character-based iteration tasks on a
  644. // Cord, use `Cord::Chars()` to retrieve this iterator.
  645. //
  646. // Example:
  647. //
  648. // void ProcessCord(const Cord& cord) {
  649. // for (char c : cord.Chars()) { ... }
  650. // }
  651. //
  652. // Note that the ordinary caveats of temporary lifetime extension apply:
  653. //
  654. // void Process() {
  655. // for (char c : CordFactory().Chars()) {
  656. // // The temporary Cord returned by CordFactory has been destroyed!
  657. // }
  658. // }
  659. CharRange Chars() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  660. // Cord::operator[]
  661. //
  662. // Gets the "i"th character of the Cord and returns it, provided that
  663. // 0 <= i < Cord.size().
  664. //
  665. // NOTE: This routine is reasonably efficient. It is roughly
  666. // logarithmic based on the number of chunks that make up the cord. Still,
  667. // if you need to iterate over the contents of a cord, you should
  668. // use a CharIterator/ChunkIterator rather than call operator[] or Get()
  669. // repeatedly in a loop.
  670. char operator[](size_t i) const;
  671. // Cord::TryFlat()
  672. //
  673. // If this cord's representation is a single flat array, returns a
  674. // string_view referencing that array. Otherwise returns nullopt.
  675. absl::optional<absl::string_view> TryFlat() const
  676. ABSL_ATTRIBUTE_LIFETIME_BOUND;
  677. // Cord::Flatten()
  678. //
  679. // Flattens the cord into a single array and returns a view of the data.
  680. //
  681. // If the cord was already flat, the contents are not modified.
  682. absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND;
  683. // Cord::Find()
  684. //
  685. // Returns an iterator to the first occurrance of the substring `needle`.
  686. //
  687. // If the substring `needle` does not occur, `Cord::char_end()` is returned.
  688. CharIterator Find(absl::string_view needle) const;
  689. CharIterator Find(const absl::Cord& needle) const;
  690. // Supports absl::Cord as a sink object for absl::Format().
  691. friend void AbslFormatFlush(absl::Nonnull<absl::Cord*> cord,
  692. absl::string_view part) {
  693. cord->Append(part);
  694. }
  695. // Support automatic stringification with absl::StrCat and absl::StrFormat.
  696. template <typename Sink>
  697. friend void AbslStringify(Sink& sink, const absl::Cord& cord) {
  698. for (absl::string_view chunk : cord.Chunks()) {
  699. sink.Append(chunk);
  700. }
  701. }
  702. // Cord::SetExpectedChecksum()
  703. //
  704. // Stores a checksum value with this non-empty cord instance, for later
  705. // retrieval.
  706. //
  707. // The expected checksum is a number stored out-of-band, alongside the data.
  708. // It is preserved across copies and assignments, but any mutations to a cord
  709. // will cause it to lose its expected checksum.
  710. //
  711. // The expected checksum is not part of a Cord's value, and does not affect
  712. // operations such as equality or hashing.
  713. //
  714. // This field is intended to store a CRC32C checksum for later validation, to
  715. // help support end-to-end checksum workflows. However, the Cord API itself
  716. // does no CRC validation, and assigns no meaning to this number.
  717. //
  718. // This call has no effect if this cord is empty.
  719. void SetExpectedChecksum(uint32_t crc);
  720. // Returns this cord's expected checksum, if it has one. Otherwise, returns
  721. // nullopt.
  722. absl::optional<uint32_t> ExpectedChecksum() const;
  723. template <typename H>
  724. friend H AbslHashValue(H hash_state, const absl::Cord& c) {
  725. absl::optional<absl::string_view> maybe_flat = c.TryFlat();
  726. if (maybe_flat.has_value()) {
  727. return H::combine(std::move(hash_state), *maybe_flat);
  728. }
  729. return c.HashFragmented(std::move(hash_state));
  730. }
  731. // Create a Cord with the contents of StringConstant<T>::value.
  732. // No allocations will be done and no data will be copied.
  733. // This is an INTERNAL API and subject to change or removal. This API can only
  734. // be used by spelling absl::strings_internal::MakeStringConstant, which is
  735. // also an internal API.
  736. template <typename T>
  737. // NOLINTNEXTLINE(google-explicit-constructor)
  738. constexpr Cord(strings_internal::StringConstant<T>);
  739. private:
  740. using CordRep = absl::cord_internal::CordRep;
  741. using CordRepFlat = absl::cord_internal::CordRepFlat;
  742. using CordzInfo = cord_internal::CordzInfo;
  743. using CordzUpdateScope = cord_internal::CordzUpdateScope;
  744. using CordzUpdateTracker = cord_internal::CordzUpdateTracker;
  745. using InlineData = cord_internal::InlineData;
  746. using MethodIdentifier = CordzUpdateTracker::MethodIdentifier;
  747. // Creates a cord instance with `method` representing the originating
  748. // public API call causing the cord to be created.
  749. explicit Cord(absl::string_view src, MethodIdentifier method);
  750. friend class CordTestPeer;
  751. friend bool operator==(const Cord& lhs, const Cord& rhs);
  752. friend bool operator==(const Cord& lhs, absl::string_view rhs);
  753. friend absl::Nullable<const CordzInfo*> GetCordzInfoForTesting(
  754. const Cord& cord);
  755. // Calls the provided function once for each cord chunk, in order. Unlike
  756. // Chunks(), this API will not allocate memory.
  757. void ForEachChunk(absl::FunctionRef<void(absl::string_view)>) const;
  758. // Allocates new contiguous storage for the contents of the cord. This is
  759. // called by Flatten() when the cord was not already flat.
  760. absl::string_view FlattenSlowPath();
  761. // Actual cord contents are hidden inside the following simple
  762. // class so that we can isolate the bulk of cord.cc from changes
  763. // to the representation.
  764. //
  765. // InlineRep holds either a tree pointer, or an array of kMaxInline bytes.
  766. class InlineRep {
  767. public:
  768. static constexpr unsigned char kMaxInline = cord_internal::kMaxInline;
  769. static_assert(kMaxInline >= sizeof(absl::cord_internal::CordRep*), "");
  770. constexpr InlineRep() : data_() {}
  771. explicit InlineRep(InlineData::DefaultInitType init) : data_(init) {}
  772. InlineRep(const InlineRep& src);
  773. InlineRep(InlineRep&& src);
  774. InlineRep& operator=(const InlineRep& src);
  775. InlineRep& operator=(InlineRep&& src) noexcept;
  776. explicit constexpr InlineRep(absl::string_view sv,
  777. absl::Nullable<CordRep*> rep);
  778. void Swap(absl::Nonnull<InlineRep*> rhs);
  779. size_t size() const;
  780. // Returns nullptr if holding pointer
  781. absl::Nullable<const char*> data() const;
  782. // Discards pointer, if any
  783. void set_data(absl::Nonnull<const char*> data, size_t n);
  784. absl::Nonnull<char*> set_data(size_t n); // Write data to the result
  785. // Returns nullptr if holding bytes
  786. absl::Nullable<absl::cord_internal::CordRep*> tree() const;
  787. absl::Nonnull<absl::cord_internal::CordRep*> as_tree() const;
  788. absl::Nonnull<const char*> as_chars() const;
  789. // Returns non-null iff was holding a pointer
  790. absl::Nullable<absl::cord_internal::CordRep*> clear();
  791. // Converts to pointer if necessary.
  792. void reduce_size(size_t n); // REQUIRES: holding data
  793. void remove_prefix(size_t n); // REQUIRES: holding data
  794. void AppendArray(absl::string_view src, MethodIdentifier method);
  795. absl::string_view FindFlatStartPiece() const;
  796. // Creates a CordRepFlat instance from the current inlined data with `extra'
  797. // bytes of desired additional capacity.
  798. absl::Nonnull<CordRepFlat*> MakeFlatWithExtraCapacity(size_t extra);
  799. // Sets the tree value for this instance. `rep` must not be null.
  800. // Requires the current instance to hold a tree, and a lock to be held on
  801. // any CordzInfo referenced by this instance. The latter is enforced through
  802. // the CordzUpdateScope argument. If the current instance is sampled, then
  803. // the CordzInfo instance is updated to reference the new `rep` value.
  804. void SetTree(absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope);
  805. // Identical to SetTree(), except that `rep` is allowed to be null, in
  806. // which case the current instance is reset to an empty value.
  807. void SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
  808. const CordzUpdateScope& scope);
  809. // Sets the tree value for this instance, and randomly samples this cord.
  810. // This function disregards existing contents in `data_`, and should be
  811. // called when a Cord is 'promoted' from an 'uninitialized' or 'inlined'
  812. // value to a non-inlined (tree / ring) value.
  813. void EmplaceTree(absl::Nonnull<CordRep*> rep, MethodIdentifier method);
  814. // Identical to EmplaceTree, except that it copies the parent stack from
  815. // the provided `parent` data if the parent is sampled.
  816. void EmplaceTree(absl::Nonnull<CordRep*> rep, const InlineData& parent,
  817. MethodIdentifier method);
  818. // Commits the change of a newly created, or updated `rep` root value into
  819. // this cord. `old_rep` indicates the old (inlined or tree) value of the
  820. // cord, and determines if the commit invokes SetTree() or EmplaceTree().
  821. void CommitTree(absl::Nullable<const CordRep*> old_rep,
  822. absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope,
  823. MethodIdentifier method);
  824. void AppendTreeToInlined(absl::Nonnull<CordRep*> tree,
  825. MethodIdentifier method);
  826. void AppendTreeToTree(absl::Nonnull<CordRep*> tree,
  827. MethodIdentifier method);
  828. void AppendTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
  829. void PrependTreeToInlined(absl::Nonnull<CordRep*> tree,
  830. MethodIdentifier method);
  831. void PrependTreeToTree(absl::Nonnull<CordRep*> tree,
  832. MethodIdentifier method);
  833. void PrependTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
  834. bool IsSame(const InlineRep& other) const { return data_ == other.data_; }
  835. void CopyTo(absl::Nonnull<std::string*> dst) const {
  836. // memcpy is much faster when operating on a known size. On most supported
  837. // platforms, the small string optimization is large enough that resizing
  838. // to 15 bytes does not cause a memory allocation.
  839. absl::strings_internal::STLStringResizeUninitialized(dst, kMaxInline);
  840. data_.copy_max_inline_to(&(*dst)[0]);
  841. // erase is faster than resize because the logic for memory allocation is
  842. // not needed.
  843. dst->erase(inline_size());
  844. }
  845. // Copies the inline contents into `dst`. Assumes the cord is not empty.
  846. void CopyToArray(absl::Nonnull<char*> dst) const;
  847. bool is_tree() const { return data_.is_tree(); }
  848. // Returns true if the Cord is being profiled by cordz.
  849. bool is_profiled() const { return data_.is_tree() && data_.is_profiled(); }
  850. // Returns the available inlined capacity, or 0 if is_tree() == true.
  851. size_t remaining_inline_capacity() const {
  852. return data_.is_tree() ? 0 : kMaxInline - data_.inline_size();
  853. }
  854. // Returns the profiled CordzInfo, or nullptr if not sampled.
  855. absl::Nullable<absl::cord_internal::CordzInfo*> cordz_info() const {
  856. return data_.cordz_info();
  857. }
  858. // Sets the profiled CordzInfo.
  859. void set_cordz_info(absl::Nonnull<cord_internal::CordzInfo*> cordz_info) {
  860. assert(cordz_info != nullptr);
  861. data_.set_cordz_info(cordz_info);
  862. }
  863. // Resets the current cordz_info to null / empty.
  864. void clear_cordz_info() { data_.clear_cordz_info(); }
  865. private:
  866. friend class Cord;
  867. void AssignSlow(const InlineRep& src);
  868. // Unrefs the tree and stops profiling.
  869. void UnrefTree();
  870. void ResetToEmpty() { data_ = {}; }
  871. void set_inline_size(size_t size) { data_.set_inline_size(size); }
  872. size_t inline_size() const { return data_.inline_size(); }
  873. // Empty cords that carry a checksum have a CordRepCrc node with a null
  874. // child node. The code can avoid lots of special cases where it would
  875. // otherwise transition from tree to inline storage if we just remove the
  876. // CordRepCrc node before mutations. Must never be called inside a
  877. // CordzUpdateScope since it untracks the cordz info.
  878. void MaybeRemoveEmptyCrcNode();
  879. cord_internal::InlineData data_;
  880. };
  881. InlineRep contents_;
  882. // Helper for GetFlat() and TryFlat().
  883. static bool GetFlatAux(absl::Nonnull<absl::cord_internal::CordRep*> rep,
  884. absl::Nonnull<absl::string_view*> fragment);
  885. // Helper for ForEachChunk().
  886. static void ForEachChunkAux(
  887. absl::Nonnull<absl::cord_internal::CordRep*> rep,
  888. absl::FunctionRef<void(absl::string_view)> callback);
  889. // The destructor for non-empty Cords.
  890. void DestroyCordSlow();
  891. // Out-of-line implementation of slower parts of logic.
  892. void CopyToArraySlowPath(absl::Nonnull<char*> dst) const;
  893. int CompareSlowPath(absl::string_view rhs, size_t compared_size,
  894. size_t size_to_compare) const;
  895. int CompareSlowPath(const Cord& rhs, size_t compared_size,
  896. size_t size_to_compare) const;
  897. bool EqualsImpl(absl::string_view rhs, size_t size_to_compare) const;
  898. bool EqualsImpl(const Cord& rhs, size_t size_to_compare) const;
  899. int CompareImpl(const Cord& rhs) const;
  900. template <typename ResultType, typename RHS>
  901. friend ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
  902. size_t size_to_compare);
  903. static absl::string_view GetFirstChunk(const Cord& c);
  904. static absl::string_view GetFirstChunk(absl::string_view sv);
  905. // Returns a new reference to contents_.tree(), or steals an existing
  906. // reference if called on an rvalue.
  907. absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() const&;
  908. absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() &&;
  909. // Helper for Append().
  910. template <typename C>
  911. void AppendImpl(C&& src);
  912. // Appends / Prepends `src` to this instance, using precise sizing.
  913. // This method does explicitly not attempt to use any spare capacity
  914. // in any pending last added private owned flat.
  915. // Requires `src` to be <= kMaxFlatLength.
  916. void AppendPrecise(absl::string_view src, MethodIdentifier method);
  917. void PrependPrecise(absl::string_view src, MethodIdentifier method);
  918. CordBuffer GetAppendBufferSlowPath(size_t block_size, size_t capacity,
  919. size_t min_capacity);
  920. // Prepends the provided data to this instance. `method` contains the public
  921. // API method for this action which is tracked for Cordz sampling purposes.
  922. void PrependArray(absl::string_view src, MethodIdentifier method);
  923. // Assigns the value in 'src' to this instance, 'stealing' its contents.
  924. // Requires src.length() > kMaxBytesToCopy.
  925. Cord& AssignLargeString(std::string&& src);
  926. // Helper for AbslHashValue().
  927. template <typename H>
  928. H HashFragmented(H hash_state) const {
  929. typename H::AbslInternalPiecewiseCombiner combiner;
  930. ForEachChunk([&combiner, &hash_state](absl::string_view chunk) {
  931. hash_state = combiner.add_buffer(std::move(hash_state), chunk.data(),
  932. chunk.size());
  933. });
  934. return H::combine(combiner.finalize(std::move(hash_state)), size());
  935. }
  936. friend class CrcCord;
  937. void SetCrcCordState(crc_internal::CrcCordState state);
  938. absl::Nullable<const crc_internal::CrcCordState*> MaybeGetCrcCordState()
  939. const;
  940. CharIterator FindImpl(CharIterator it, absl::string_view needle) const;
  941. };
  942. ABSL_NAMESPACE_END
  943. } // namespace absl
  944. namespace absl {
  945. ABSL_NAMESPACE_BEGIN
  946. // allow a Cord to be logged
  947. extern std::ostream& operator<<(std::ostream& out, const Cord& cord);
  948. // ------------------------------------------------------------------
  949. // Internal details follow. Clients should ignore.
  950. namespace cord_internal {
  951. // Does non-template-specific `CordRepExternal` initialization.
  952. // Requires `data` to be non-empty.
  953. void InitializeCordRepExternal(absl::string_view data,
  954. absl::Nonnull<CordRepExternal*> rep);
  955. // Creates a new `CordRep` that owns `data` and `releaser` and returns a pointer
  956. // to it. Requires `data` to be non-empty.
  957. template <typename Releaser>
  958. // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
  959. absl::Nonnull<CordRep*> NewExternalRep(absl::string_view data,
  960. Releaser&& releaser) {
  961. assert(!data.empty());
  962. using ReleaserType = absl::decay_t<Releaser>;
  963. CordRepExternal* rep = new CordRepExternalImpl<ReleaserType>(
  964. std::forward<Releaser>(releaser), 0);
  965. InitializeCordRepExternal(data, rep);
  966. return rep;
  967. }
  968. // Overload for function reference types that dispatches using a function
  969. // pointer because there are no `alignof()` or `sizeof()` a function reference.
  970. // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
  971. inline absl::Nonnull<CordRep*> NewExternalRep(absl::string_view data,
  972. void (&releaser)(absl::string_view)) {
  973. return NewExternalRep(data, &releaser);
  974. }
  975. } // namespace cord_internal
  976. template <typename Releaser>
  977. Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser) {
  978. Cord cord;
  979. if (ABSL_PREDICT_TRUE(!data.empty())) {
  980. cord.contents_.EmplaceTree(::absl::cord_internal::NewExternalRep(
  981. data, std::forward<Releaser>(releaser)),
  982. Cord::MethodIdentifier::kMakeCordFromExternal);
  983. } else {
  984. using ReleaserType = absl::decay_t<Releaser>;
  985. cord_internal::InvokeReleaser(
  986. cord_internal::Rank0{}, ReleaserType(std::forward<Releaser>(releaser)),
  987. data);
  988. }
  989. return cord;
  990. }
  991. constexpr Cord::InlineRep::InlineRep(absl::string_view sv,
  992. absl::Nullable<CordRep*> rep)
  993. : data_(sv, rep) {}
  994. inline Cord::InlineRep::InlineRep(const Cord::InlineRep& src)
  995. : data_(InlineData::kDefaultInit) {
  996. if (CordRep* tree = src.tree()) {
  997. EmplaceTree(CordRep::Ref(tree), src.data_,
  998. CordzUpdateTracker::kConstructorCord);
  999. } else {
  1000. data_ = src.data_;
  1001. }
  1002. }
  1003. inline Cord::InlineRep::InlineRep(Cord::InlineRep&& src) : data_(src.data_) {
  1004. src.ResetToEmpty();
  1005. }
  1006. inline Cord::InlineRep& Cord::InlineRep::operator=(const Cord::InlineRep& src) {
  1007. if (this == &src) {
  1008. return *this;
  1009. }
  1010. if (!is_tree() && !src.is_tree()) {
  1011. data_ = src.data_;
  1012. return *this;
  1013. }
  1014. AssignSlow(src);
  1015. return *this;
  1016. }
  1017. inline Cord::InlineRep& Cord::InlineRep::operator=(
  1018. Cord::InlineRep&& src) noexcept {
  1019. if (is_tree()) {
  1020. UnrefTree();
  1021. }
  1022. data_ = src.data_;
  1023. src.ResetToEmpty();
  1024. return *this;
  1025. }
  1026. inline void Cord::InlineRep::Swap(absl::Nonnull<Cord::InlineRep*> rhs) {
  1027. if (rhs == this) {
  1028. return;
  1029. }
  1030. std::swap(data_, rhs->data_);
  1031. }
  1032. inline absl::Nullable<const char*> Cord::InlineRep::data() const {
  1033. return is_tree() ? nullptr : data_.as_chars();
  1034. }
  1035. inline absl::Nonnull<const char*> Cord::InlineRep::as_chars() const {
  1036. assert(!data_.is_tree());
  1037. return data_.as_chars();
  1038. }
  1039. inline absl::Nonnull<absl::cord_internal::CordRep*> Cord::InlineRep::as_tree()
  1040. const {
  1041. assert(data_.is_tree());
  1042. return data_.as_tree();
  1043. }
  1044. inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::tree()
  1045. const {
  1046. if (is_tree()) {
  1047. return as_tree();
  1048. } else {
  1049. return nullptr;
  1050. }
  1051. }
  1052. inline size_t Cord::InlineRep::size() const {
  1053. return is_tree() ? as_tree()->length : inline_size();
  1054. }
  1055. inline absl::Nonnull<cord_internal::CordRepFlat*>
  1056. Cord::InlineRep::MakeFlatWithExtraCapacity(size_t extra) {
  1057. static_assert(cord_internal::kMinFlatLength >= sizeof(data_), "");
  1058. size_t len = data_.inline_size();
  1059. auto* result = CordRepFlat::New(len + extra);
  1060. result->length = len;
  1061. data_.copy_max_inline_to(result->Data());
  1062. return result;
  1063. }
  1064. inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
  1065. MethodIdentifier method) {
  1066. assert(rep);
  1067. data_.make_tree(rep);
  1068. CordzInfo::MaybeTrackCord(data_, method);
  1069. }
  1070. inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
  1071. const InlineData& parent,
  1072. MethodIdentifier method) {
  1073. data_.make_tree(rep);
  1074. CordzInfo::MaybeTrackCord(data_, parent, method);
  1075. }
  1076. inline void Cord::InlineRep::SetTree(absl::Nonnull<CordRep*> rep,
  1077. const CordzUpdateScope& scope) {
  1078. assert(rep);
  1079. assert(data_.is_tree());
  1080. data_.set_tree(rep);
  1081. scope.SetCordRep(rep);
  1082. }
  1083. inline void Cord::InlineRep::SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
  1084. const CordzUpdateScope& scope) {
  1085. assert(data_.is_tree());
  1086. if (rep) {
  1087. data_.set_tree(rep);
  1088. } else {
  1089. data_ = {};
  1090. }
  1091. scope.SetCordRep(rep);
  1092. }
  1093. inline void Cord::InlineRep::CommitTree(absl::Nullable<const CordRep*> old_rep,
  1094. absl::Nonnull<CordRep*> rep,
  1095. const CordzUpdateScope& scope,
  1096. MethodIdentifier method) {
  1097. if (old_rep) {
  1098. SetTree(rep, scope);
  1099. } else {
  1100. EmplaceTree(rep, method);
  1101. }
  1102. }
  1103. inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::clear() {
  1104. if (is_tree()) {
  1105. CordzInfo::MaybeUntrackCord(cordz_info());
  1106. }
  1107. absl::cord_internal::CordRep* result = tree();
  1108. ResetToEmpty();
  1109. return result;
  1110. }
  1111. inline void Cord::InlineRep::CopyToArray(absl::Nonnull<char*> dst) const {
  1112. assert(!is_tree());
  1113. size_t n = inline_size();
  1114. assert(n != 0);
  1115. cord_internal::SmallMemmove(dst, data_.as_chars(), n);
  1116. }
  1117. inline void Cord::InlineRep::MaybeRemoveEmptyCrcNode() {
  1118. CordRep* rep = tree();
  1119. if (rep == nullptr || ABSL_PREDICT_TRUE(rep->length > 0)) {
  1120. return;
  1121. }
  1122. assert(rep->IsCrc());
  1123. assert(rep->crc()->child == nullptr);
  1124. CordzInfo::MaybeUntrackCord(cordz_info());
  1125. CordRep::Unref(rep);
  1126. ResetToEmpty();
  1127. }
  1128. constexpr inline Cord::Cord() noexcept {}
  1129. inline Cord::Cord(absl::string_view src)
  1130. : Cord(src, CordzUpdateTracker::kConstructorString) {}
  1131. template <typename T>
  1132. constexpr Cord::Cord(strings_internal::StringConstant<T>)
  1133. : contents_(strings_internal::StringConstant<T>::value,
  1134. strings_internal::StringConstant<T>::value.size() <=
  1135. cord_internal::kMaxInline
  1136. ? nullptr
  1137. : &cord_internal::ConstInitExternalStorage<
  1138. strings_internal::StringConstant<T>>::value) {}
  1139. inline Cord& Cord::operator=(const Cord& x) {
  1140. contents_ = x.contents_;
  1141. return *this;
  1142. }
  1143. template <typename T, Cord::EnableIfString<T>>
  1144. Cord& Cord::operator=(T&& src) {
  1145. if (src.size() <= cord_internal::kMaxBytesToCopy) {
  1146. return operator=(absl::string_view(src));
  1147. } else {
  1148. return AssignLargeString(std::forward<T>(src));
  1149. }
  1150. }
  1151. inline Cord::Cord(const Cord& src) : contents_(src.contents_) {}
  1152. inline Cord::Cord(Cord&& src) noexcept : contents_(std::move(src.contents_)) {}
  1153. inline void Cord::swap(Cord& other) noexcept {
  1154. contents_.Swap(&other.contents_);
  1155. }
  1156. inline Cord& Cord::operator=(Cord&& x) noexcept {
  1157. contents_ = std::move(x.contents_);
  1158. return *this;
  1159. }
  1160. extern template Cord::Cord(std::string&& src);
  1161. inline size_t Cord::size() const {
  1162. // Length is 1st field in str.rep_
  1163. return contents_.size();
  1164. }
  1165. inline bool Cord::empty() const { return size() == 0; }
  1166. inline size_t Cord::EstimatedMemoryUsage(
  1167. CordMemoryAccounting accounting_method) const {
  1168. size_t result = sizeof(Cord);
  1169. if (const absl::cord_internal::CordRep* rep = contents_.tree()) {
  1170. switch (accounting_method) {
  1171. case CordMemoryAccounting::kFairShare:
  1172. result += cord_internal::GetEstimatedFairShareMemoryUsage(rep);
  1173. break;
  1174. case CordMemoryAccounting::kTotalMorePrecise:
  1175. result += cord_internal::GetMorePreciseMemoryUsage(rep);
  1176. break;
  1177. case CordMemoryAccounting::kTotal:
  1178. result += cord_internal::GetEstimatedMemoryUsage(rep);
  1179. break;
  1180. }
  1181. }
  1182. return result;
  1183. }
  1184. inline absl::optional<absl::string_view> Cord::TryFlat() const {
  1185. absl::cord_internal::CordRep* rep = contents_.tree();
  1186. if (rep == nullptr) {
  1187. return absl::string_view(contents_.data(), contents_.size());
  1188. }
  1189. absl::string_view fragment;
  1190. if (GetFlatAux(rep, &fragment)) {
  1191. return fragment;
  1192. }
  1193. return absl::nullopt;
  1194. }
  1195. inline absl::string_view Cord::Flatten() {
  1196. absl::cord_internal::CordRep* rep = contents_.tree();
  1197. if (rep == nullptr) {
  1198. return absl::string_view(contents_.data(), contents_.size());
  1199. } else {
  1200. absl::string_view already_flat_contents;
  1201. if (GetFlatAux(rep, &already_flat_contents)) {
  1202. return already_flat_contents;
  1203. }
  1204. }
  1205. return FlattenSlowPath();
  1206. }
  1207. inline void Cord::Append(absl::string_view src) {
  1208. contents_.AppendArray(src, CordzUpdateTracker::kAppendString);
  1209. }
  1210. inline void Cord::Prepend(absl::string_view src) {
  1211. PrependArray(src, CordzUpdateTracker::kPrependString);
  1212. }
  1213. inline void Cord::Append(CordBuffer buffer) {
  1214. if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
  1215. absl::string_view short_value;
  1216. if (CordRep* rep = buffer.ConsumeValue(short_value)) {
  1217. contents_.AppendTree(rep, CordzUpdateTracker::kAppendCordBuffer);
  1218. } else {
  1219. AppendPrecise(short_value, CordzUpdateTracker::kAppendCordBuffer);
  1220. }
  1221. }
  1222. inline void Cord::Prepend(CordBuffer buffer) {
  1223. if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
  1224. absl::string_view short_value;
  1225. if (CordRep* rep = buffer.ConsumeValue(short_value)) {
  1226. contents_.PrependTree(rep, CordzUpdateTracker::kPrependCordBuffer);
  1227. } else {
  1228. PrependPrecise(short_value, CordzUpdateTracker::kPrependCordBuffer);
  1229. }
  1230. }
  1231. inline CordBuffer Cord::GetAppendBuffer(size_t capacity, size_t min_capacity) {
  1232. if (empty()) return CordBuffer::CreateWithDefaultLimit(capacity);
  1233. return GetAppendBufferSlowPath(0, capacity, min_capacity);
  1234. }
  1235. inline CordBuffer Cord::GetCustomAppendBuffer(size_t block_size,
  1236. size_t capacity,
  1237. size_t min_capacity) {
  1238. if (empty()) {
  1239. return block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity)
  1240. : CordBuffer::CreateWithDefaultLimit(capacity);
  1241. }
  1242. return GetAppendBufferSlowPath(block_size, capacity, min_capacity);
  1243. }
  1244. extern template void Cord::Append(std::string&& src);
  1245. extern template void Cord::Prepend(std::string&& src);
  1246. inline int Cord::Compare(const Cord& rhs) const {
  1247. if (!contents_.is_tree() && !rhs.contents_.is_tree()) {
  1248. return contents_.data_.Compare(rhs.contents_.data_);
  1249. }
  1250. return CompareImpl(rhs);
  1251. }
  1252. // Does 'this' cord start/end with rhs
  1253. inline bool Cord::StartsWith(const Cord& rhs) const {
  1254. if (contents_.IsSame(rhs.contents_)) return true;
  1255. size_t rhs_size = rhs.size();
  1256. if (size() < rhs_size) return false;
  1257. return EqualsImpl(rhs, rhs_size);
  1258. }
  1259. inline bool Cord::StartsWith(absl::string_view rhs) const {
  1260. size_t rhs_size = rhs.size();
  1261. if (size() < rhs_size) return false;
  1262. return EqualsImpl(rhs, rhs_size);
  1263. }
  1264. inline void Cord::ChunkIterator::InitTree(
  1265. absl::Nonnull<cord_internal::CordRep*> tree) {
  1266. tree = cord_internal::SkipCrcNode(tree);
  1267. if (tree->tag == cord_internal::BTREE) {
  1268. current_chunk_ = btree_reader_.Init(tree->btree());
  1269. } else {
  1270. current_leaf_ = tree;
  1271. current_chunk_ = cord_internal::EdgeData(tree);
  1272. }
  1273. }
  1274. inline Cord::ChunkIterator::ChunkIterator(
  1275. absl::Nonnull<cord_internal::CordRep*> tree) {
  1276. bytes_remaining_ = tree->length;
  1277. InitTree(tree);
  1278. }
  1279. inline Cord::ChunkIterator::ChunkIterator(absl::Nonnull<const Cord*> cord) {
  1280. if (CordRep* tree = cord->contents_.tree()) {
  1281. bytes_remaining_ = tree->length;
  1282. if (ABSL_PREDICT_TRUE(bytes_remaining_ != 0)) {
  1283. InitTree(tree);
  1284. } else {
  1285. current_chunk_ = {};
  1286. }
  1287. } else {
  1288. bytes_remaining_ = cord->contents_.inline_size();
  1289. current_chunk_ = {cord->contents_.data(), bytes_remaining_};
  1290. }
  1291. }
  1292. inline Cord::ChunkIterator& Cord::ChunkIterator::AdvanceBtree() {
  1293. current_chunk_ = btree_reader_.Next();
  1294. return *this;
  1295. }
  1296. inline void Cord::ChunkIterator::AdvanceBytesBtree(size_t n) {
  1297. assert(n >= current_chunk_.size());
  1298. bytes_remaining_ -= n;
  1299. if (bytes_remaining_) {
  1300. if (n == current_chunk_.size()) {
  1301. current_chunk_ = btree_reader_.Next();
  1302. } else {
  1303. size_t offset = btree_reader_.length() - bytes_remaining_;
  1304. current_chunk_ = btree_reader_.Seek(offset);
  1305. }
  1306. } else {
  1307. current_chunk_ = {};
  1308. }
  1309. }
  1310. inline Cord::ChunkIterator& Cord::ChunkIterator::operator++() {
  1311. ABSL_HARDENING_ASSERT(bytes_remaining_ > 0 &&
  1312. "Attempted to iterate past `end()`");
  1313. assert(bytes_remaining_ >= current_chunk_.size());
  1314. bytes_remaining_ -= current_chunk_.size();
  1315. if (bytes_remaining_ > 0) {
  1316. if (btree_reader_) {
  1317. return AdvanceBtree();
  1318. } else {
  1319. assert(!current_chunk_.empty()); // Called on invalid iterator.
  1320. }
  1321. current_chunk_ = {};
  1322. }
  1323. return *this;
  1324. }
  1325. inline Cord::ChunkIterator Cord::ChunkIterator::operator++(int) {
  1326. ChunkIterator tmp(*this);
  1327. operator++();
  1328. return tmp;
  1329. }
  1330. inline bool Cord::ChunkIterator::operator==(const ChunkIterator& other) const {
  1331. return bytes_remaining_ == other.bytes_remaining_;
  1332. }
  1333. inline bool Cord::ChunkIterator::operator!=(const ChunkIterator& other) const {
  1334. return !(*this == other);
  1335. }
  1336. inline Cord::ChunkIterator::reference Cord::ChunkIterator::operator*() const {
  1337. ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
  1338. return current_chunk_;
  1339. }
  1340. inline Cord::ChunkIterator::pointer Cord::ChunkIterator::operator->() const {
  1341. ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
  1342. return &current_chunk_;
  1343. }
  1344. inline void Cord::ChunkIterator::RemoveChunkPrefix(size_t n) {
  1345. assert(n < current_chunk_.size());
  1346. current_chunk_.remove_prefix(n);
  1347. bytes_remaining_ -= n;
  1348. }
  1349. inline void Cord::ChunkIterator::AdvanceBytes(size_t n) {
  1350. assert(bytes_remaining_ >= n);
  1351. if (ABSL_PREDICT_TRUE(n < current_chunk_.size())) {
  1352. RemoveChunkPrefix(n);
  1353. } else if (n != 0) {
  1354. if (btree_reader_) {
  1355. AdvanceBytesBtree(n);
  1356. } else {
  1357. bytes_remaining_ = 0;
  1358. }
  1359. }
  1360. }
  1361. inline Cord::ChunkIterator Cord::chunk_begin() const {
  1362. return ChunkIterator(this);
  1363. }
  1364. inline Cord::ChunkIterator Cord::chunk_end() const { return ChunkIterator(); }
  1365. inline Cord::ChunkIterator Cord::ChunkRange::begin() const {
  1366. return cord_->chunk_begin();
  1367. }
  1368. inline Cord::ChunkIterator Cord::ChunkRange::end() const {
  1369. return cord_->chunk_end();
  1370. }
  1371. inline Cord::ChunkRange Cord::Chunks() const { return ChunkRange(this); }
  1372. inline Cord::CharIterator& Cord::CharIterator::operator++() {
  1373. if (ABSL_PREDICT_TRUE(chunk_iterator_->size() > 1)) {
  1374. chunk_iterator_.RemoveChunkPrefix(1);
  1375. } else {
  1376. ++chunk_iterator_;
  1377. }
  1378. return *this;
  1379. }
  1380. inline Cord::CharIterator Cord::CharIterator::operator++(int) {
  1381. CharIterator tmp(*this);
  1382. operator++();
  1383. return tmp;
  1384. }
  1385. inline bool Cord::CharIterator::operator==(const CharIterator& other) const {
  1386. return chunk_iterator_ == other.chunk_iterator_;
  1387. }
  1388. inline bool Cord::CharIterator::operator!=(const CharIterator& other) const {
  1389. return !(*this == other);
  1390. }
  1391. inline Cord::CharIterator::reference Cord::CharIterator::operator*() const {
  1392. return *chunk_iterator_->data();
  1393. }
  1394. inline Cord::CharIterator::pointer Cord::CharIterator::operator->() const {
  1395. return chunk_iterator_->data();
  1396. }
  1397. inline Cord Cord::AdvanceAndRead(absl::Nonnull<CharIterator*> it,
  1398. size_t n_bytes) {
  1399. assert(it != nullptr);
  1400. return it->chunk_iterator_.AdvanceAndReadBytes(n_bytes);
  1401. }
  1402. inline void Cord::Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes) {
  1403. assert(it != nullptr);
  1404. it->chunk_iterator_.AdvanceBytes(n_bytes);
  1405. }
  1406. inline absl::string_view Cord::ChunkRemaining(const CharIterator& it) {
  1407. return *it.chunk_iterator_;
  1408. }
  1409. inline Cord::CharIterator Cord::char_begin() const {
  1410. return CharIterator(this);
  1411. }
  1412. inline Cord::CharIterator Cord::char_end() const { return CharIterator(); }
  1413. inline Cord::CharIterator Cord::CharRange::begin() const {
  1414. return cord_->char_begin();
  1415. }
  1416. inline Cord::CharIterator Cord::CharRange::end() const {
  1417. return cord_->char_end();
  1418. }
  1419. inline Cord::CharRange Cord::Chars() const { return CharRange(this); }
  1420. inline void Cord::ForEachChunk(
  1421. absl::FunctionRef<void(absl::string_view)> callback) const {
  1422. absl::cord_internal::CordRep* rep = contents_.tree();
  1423. if (rep == nullptr) {
  1424. callback(absl::string_view(contents_.data(), contents_.size()));
  1425. } else {
  1426. ForEachChunkAux(rep, callback);
  1427. }
  1428. }
  1429. // Nonmember Cord-to-Cord relational operators.
  1430. inline bool operator==(const Cord& lhs, const Cord& rhs) {
  1431. if (lhs.contents_.IsSame(rhs.contents_)) return true;
  1432. size_t rhs_size = rhs.size();
  1433. if (lhs.size() != rhs_size) return false;
  1434. return lhs.EqualsImpl(rhs, rhs_size);
  1435. }
  1436. inline bool operator!=(const Cord& x, const Cord& y) { return !(x == y); }
  1437. inline bool operator<(const Cord& x, const Cord& y) { return x.Compare(y) < 0; }
  1438. inline bool operator>(const Cord& x, const Cord& y) { return x.Compare(y) > 0; }
  1439. inline bool operator<=(const Cord& x, const Cord& y) {
  1440. return x.Compare(y) <= 0;
  1441. }
  1442. inline bool operator>=(const Cord& x, const Cord& y) {
  1443. return x.Compare(y) >= 0;
  1444. }
  1445. // Nonmember Cord-to-absl::string_view relational operators.
  1446. //
  1447. // Due to implicit conversions, these also enable comparisons of Cord with
  1448. // std::string and const char*.
  1449. inline bool operator==(const Cord& lhs, absl::string_view rhs) {
  1450. size_t lhs_size = lhs.size();
  1451. size_t rhs_size = rhs.size();
  1452. if (lhs_size != rhs_size) return false;
  1453. return lhs.EqualsImpl(rhs, rhs_size);
  1454. }
  1455. inline bool operator==(absl::string_view x, const Cord& y) { return y == x; }
  1456. inline bool operator!=(const Cord& x, absl::string_view y) { return !(x == y); }
  1457. inline bool operator!=(absl::string_view x, const Cord& y) { return !(x == y); }
  1458. inline bool operator<(const Cord& x, absl::string_view y) {
  1459. return x.Compare(y) < 0;
  1460. }
  1461. inline bool operator<(absl::string_view x, const Cord& y) {
  1462. return y.Compare(x) > 0;
  1463. }
  1464. inline bool operator>(const Cord& x, absl::string_view y) { return y < x; }
  1465. inline bool operator>(absl::string_view x, const Cord& y) { return y < x; }
  1466. inline bool operator<=(const Cord& x, absl::string_view y) { return !(y < x); }
  1467. inline bool operator<=(absl::string_view x, const Cord& y) { return !(y < x); }
  1468. inline bool operator>=(const Cord& x, absl::string_view y) { return !(x < y); }
  1469. inline bool operator>=(absl::string_view x, const Cord& y) { return !(x < y); }
  1470. // Some internals exposed to test code.
  1471. namespace strings_internal {
  1472. class CordTestAccess {
  1473. public:
  1474. static size_t FlatOverhead();
  1475. static size_t MaxFlatLength();
  1476. static size_t SizeofCordRepExternal();
  1477. static size_t SizeofCordRepSubstring();
  1478. static size_t FlatTagToLength(uint8_t tag);
  1479. static uint8_t LengthToTag(size_t s);
  1480. };
  1481. } // namespace strings_internal
  1482. ABSL_NAMESPACE_END
  1483. } // namespace absl
  1484. #endif // ABSL_STRINGS_CORD_H_