LineReader.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2013-present Facebook, Inc.
  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. #include <folly/experimental/symbolizer/LineReader.h>
  17. #include <cstring>
  18. #include <folly/FileUtil.h>
  19. namespace folly {
  20. namespace symbolizer {
  21. LineReader::LineReader(int fd, char* buf, size_t bufSize)
  22. : fd_(fd),
  23. buf_(buf),
  24. bufEnd_(buf_ + bufSize),
  25. bol_(buf),
  26. eol_(buf),
  27. end_(buf),
  28. state_(kReading) {}
  29. LineReader::State LineReader::readLine(StringPiece& line) {
  30. bol_ = eol_; // Start past what we already returned
  31. for (;;) {
  32. // Search for newline
  33. char* newline = static_cast<char*>(memchr(eol_, '\n', end_ - eol_));
  34. if (newline) {
  35. eol_ = newline + 1;
  36. break;
  37. } else if (state_ != kReading || (bol_ == buf_ && end_ == bufEnd_)) {
  38. // If the buffer is full with one line (line too long), or we're
  39. // at the end of the file, return what we have.
  40. eol_ = end_;
  41. break;
  42. }
  43. // We don't have a full line in the buffer, but we have room to read.
  44. // Move to the beginning of the buffer.
  45. memmove(buf_, eol_, end_ - eol_);
  46. end_ -= (eol_ - buf_);
  47. bol_ = buf_;
  48. eol_ = end_;
  49. // Refill
  50. ssize_t available = bufEnd_ - end_;
  51. ssize_t n = readFull(fd_, end_, available);
  52. if (n < 0) {
  53. state_ = kError;
  54. n = 0;
  55. } else if (n < available) {
  56. state_ = kEof;
  57. }
  58. end_ += n;
  59. }
  60. line.assign(bol_, eol_);
  61. return eol_ != bol_ ? kReading : state_;
  62. }
  63. } // namespace symbolizer
  64. } // namespace folly