1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <errno.h>
18 #include <string.h>
19 #include <unistd.h>
20
21 #include "LineBuffer.h"
22
LineBuffer(int fd,char * buffer,size_t buffer_len)23 LineBuffer::LineBuffer(int fd, char* buffer, size_t buffer_len) : fd_(fd), buffer_(buffer), buffer_len_(buffer_len) {
24 }
25
GetLine(char ** line,size_t * line_len)26 bool LineBuffer::GetLine(char** line, size_t* line_len) {
27 while (true) {
28 if (bytes_ > 0) {
29 char* newline = reinterpret_cast<char*>(memchr(buffer_ + start_, '\n', bytes_));
30 if (newline != nullptr) {
31 *newline = '\0';
32 *line = buffer_ + start_;
33 start_ = newline - buffer_ + 1;
34 bytes_ -= newline - *line + 1;
35 *line_len = newline - *line;
36 return true;
37 }
38 }
39 if (start_ > 0) {
40 // Didn't find anything, copy the current to the front of the buffer.
41 memmove(buffer_, buffer_ + start_, bytes_);
42 start_ = 0;
43 }
44 ssize_t bytes = TEMP_FAILURE_RETRY(read(fd_, buffer_ + bytes_, buffer_len_ - bytes_ - 1));
45 if (bytes <= 0) {
46 if (bytes_ > 0) {
47 // The read data might not contain a nul terminator, so add one.
48 buffer_[bytes_] = '\0';
49 *line = buffer_ + start_;
50 *line_len = bytes_;
51 bytes_ = 0;
52 start_ = 0;
53 return true;
54 }
55 return false;
56 }
57 bytes_ += bytes;
58 }
59 }
60