1 // Copyright 2022 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 #ifndef ABSL_STRINGS_INTERNAL_CORD_DATA_EDGE_H_ 16 #define ABSL_STRINGS_INTERNAL_CORD_DATA_EDGE_H_ 17 18 #include <cassert> 19 #include <cstddef> 20 21 #include "absl/base/config.h" 22 #include "absl/strings/internal/cord_internal.h" 23 #include "absl/strings/internal/cord_rep_flat.h" 24 #include "absl/strings/string_view.h" 25 26 namespace absl { 27 ABSL_NAMESPACE_BEGIN 28 namespace cord_internal { 29 30 // Returns true if the provided rep is a FLAT, EXTERNAL or a SUBSTRING node 31 // holding a FLAT or EXTERNAL child rep. Requires `rep != nullptr`. IsDataEdge(const CordRep * edge)32inline bool IsDataEdge(const CordRep* edge) { 33 assert(edge != nullptr); 34 35 // The fast path is that `edge` is an EXTERNAL or FLAT node, making the below 36 // if a single, well predicted branch. We then repeat the FLAT or EXTERNAL 37 // check in the slow path of the SUBSTRING check to optimize for the hot path. 38 if (edge->tag == EXTERNAL || edge->tag >= FLAT) return true; 39 if (edge->tag == SUBSTRING) edge = edge->substring()->child; 40 return edge->tag == EXTERNAL || edge->tag >= FLAT; 41 } 42 43 // Returns the `absl::string_view` data reference for the provided data edge. 44 // Requires 'IsDataEdge(edge) == true`. EdgeData(const CordRep * edge)45inline absl::string_view EdgeData(const CordRep* edge) { 46 assert(IsDataEdge(edge)); 47 48 size_t offset = 0; 49 const size_t length = edge->length; 50 if (edge->IsSubstring()) { 51 offset = edge->substring()->start; 52 edge = edge->substring()->child; 53 } 54 return edge->tag >= FLAT 55 ? absl::string_view{edge->flat()->Data() + offset, length} 56 : absl::string_view{edge->external()->base + offset, length}; 57 } 58 59 } // namespace cord_internal 60 ABSL_NAMESPACE_END 61 } // namespace absl 62 63 #endif // ABSL_STRINGS_INTERNAL_CORD_DATA_EDGE_H_ 64