2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 // Copyright 2004-present Facebook. All Rights Reserved.
24 * Helper classes for use with CursorBase::readWhile()
26 class CursorStringAppender {
28 void append(ByteRange bytes) {
29 str_.append(reinterpret_cast<char const*>(bytes.data()), bytes.size());
31 std::string extractString() {
32 return std::move(str_);
39 class CursorNoopAppender {
41 void append(ByteRange) {}
44 template <class Derived, class BufType>
45 std::string CursorBase<Derived, BufType>::readTerminatedString(
49 auto keepReading = [&bytesRead, termChar, maxLength](uint8_t byte) {
50 if (byte == termChar) {
54 if (bytesRead >= maxLength) {
55 throw std::length_error("string overflow");
60 auto result = readWhile(keepReading);
61 // skip over the terminator character
63 throw std::out_of_range("terminator not found");
70 template <class Derived, class BufType>
71 template <typename Predicate>
72 std::string CursorBase<Derived, BufType>::readWhile(
73 const Predicate& predicate) {
74 CursorStringAppender s;
75 readWhile(predicate, s);
76 return s.extractString();
79 template <class Derived, class BufType>
80 template <typename Predicate, typename Output>
81 void CursorBase<Derived, BufType>::readWhile(
82 const Predicate& predicate,
85 auto peeked = peekBytes();
89 for (size_t idx = 0; idx < peeked.size(); ++idx) {
90 if (!predicate(peeked[idx])) {
91 peeked.reset(peeked.data(), idx);
102 template <class Derived, class BufType>
103 template <typename Predicate>
104 void CursorBase<Derived, BufType>::skipWhile(const Predicate& predicate) {
105 CursorNoopAppender appender;
106 readWhile(predicate, appender);
110 } // folly::io::detail