LineReader.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #pragma once
  17. #include <cstddef>
  18. #include <boost/noncopyable.hpp>
  19. #include <folly/Range.h>
  20. namespace folly {
  21. namespace symbolizer {
  22. /**
  23. * Async-signal-safe line reader.
  24. */
  25. class LineReader : private boost::noncopyable {
  26. public:
  27. /**
  28. * Create a line reader that reads into a user-provided buffer (of size
  29. * bufSize).
  30. */
  31. LineReader(int fd, char* buf, size_t bufSize);
  32. enum State {
  33. kReading,
  34. kEof,
  35. kError,
  36. };
  37. /**
  38. * Read the next line from the file.
  39. *
  40. * If the line is at most bufSize characters long, including the trailing
  41. * newline, it will be returned (including the trailing newline).
  42. *
  43. * If the line is longer than bufSize, we return the first bufSize bytes
  44. * (which won't include a trailing newline) and then continue from that
  45. * point onwards.
  46. *
  47. * The lines returned are not null-terminated.
  48. *
  49. * Returns kReading with a valid line, kEof if at end of file, or kError
  50. * if a read error was encountered.
  51. *
  52. * Example:
  53. * bufSize = 10
  54. * input has "hello world\n"
  55. * The first call returns "hello worl"
  56. * The second call returns "d\n"
  57. */
  58. State readLine(StringPiece& line);
  59. private:
  60. int const fd_;
  61. char* const buf_;
  62. char* const bufEnd_;
  63. // buf_ <= bol_ <= eol_ <= end_ <= bufEnd_
  64. //
  65. // [buf_, end_): current buffer contents (read from file)
  66. //
  67. // [buf_, bol_): free (already processed, can be discarded)
  68. // [bol_, eol_): current line, including \n if it exists, eol_ points
  69. // 1 character past the \n
  70. // [eol_, end_): read, unprocessed
  71. // [end_, bufEnd_): free
  72. char* bol_;
  73. char* eol_;
  74. char* end_;
  75. State state_;
  76. };
  77. } // namespace symbolizer
  78. } // namespace folly