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