1 // Copyright 2021 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 #include "absl/strings/internal/cord_rep_consume.h"
16
17 #include <array>
18 #include <utility>
19
20 #include "absl/container/inlined_vector.h"
21 #include "absl/functional/function_ref.h"
22 #include "absl/strings/internal/cord_internal.h"
23
24 namespace absl {
25 ABSL_NAMESPACE_BEGIN
26 namespace cord_internal {
27
28 namespace {
29
30 // Unrefs the provided `substring`, and returns `substring->child`
31 // Adds or assumes a reference on `substring->child`
ClipSubstring(CordRepSubstring * substring)32 CordRep* ClipSubstring(CordRepSubstring* substring) {
33 CordRep* child = substring->child;
34 if (substring->refcount.IsOne()) {
35 delete substring;
36 } else {
37 CordRep::Ref(child);
38 CordRep::Unref(substring);
39 }
40 return child;
41 }
42
43 } // namespace
44
Consume(CordRep * rep,ConsumeFn consume_fn)45 void Consume(CordRep* rep, ConsumeFn consume_fn) {
46 size_t offset = 0;
47 size_t length = rep->length;
48
49 if (rep->tag == SUBSTRING) {
50 offset += rep->substring()->start;
51 rep = ClipSubstring(rep->substring());
52 }
53 consume_fn(rep, offset, length);
54 }
55
ReverseConsume(CordRep * rep,ConsumeFn consume_fn)56 void ReverseConsume(CordRep* rep, ConsumeFn consume_fn) {
57 return Consume(rep, std::move(consume_fn));
58 }
59
60 } // namespace cord_internal
61 ABSL_NAMESPACE_END
62 } // namespace absl
63