2 * Copyright (C) 2015 The Android Open Source Project
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.
21 #include "LineBuffer.h"
23 LineBuffer::LineBuffer(int fd, char* buffer, size_t buffer_len) : fd_(fd), buffer_(buffer), buffer_len_(buffer_len) {
26 bool LineBuffer::GetLine(char** line, size_t* line_len) {
29 char* newline = reinterpret_cast<char*>(memchr(buffer_ + start_, '\n', bytes_));
30 if (newline != nullptr) {
32 *line = buffer_ + start_;
33 start_ = newline - buffer_ + 1;
34 bytes_ -= newline - *line + 1;
35 *line_len = newline - *line;
40 // Didn't find anything, copy the current to the front of the buffer.
41 memmove(buffer_, buffer_ + start_, bytes_);
44 ssize_t bytes = TEMP_FAILURE_RETRY(read(fd_, buffer_ + bytes_, buffer_len_ - bytes_ - 1));
47 // The read data might not contain a nul terminator, so add one.
48 buffer_[bytes_] = '\0';
49 *line = buffer_ + start_;