FLANG

char-buffer.h
1 //===-- include/flang/Parser/char-buffer.h ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef FORTRAN_PARSER_CHAR_BUFFER_H_
10 #define FORTRAN_PARSER_CHAR_BUFFER_H_
11
12 // Defines a simple expandable buffer suitable for efficiently accumulating
13 // a stream of bytes.
14
15 #include <cstddef>
16 #include <forward_list>
17 #include <string>
18 #include <utility>
19 #include <vector>
20
21 namespace Fortran::parser {
22
23 class CharBuffer {
24 public:
25 CharBuffer() {}
26 CharBuffer(CharBuffer &&that)
27 : blocks_(std::move(that.blocks_)), last_{that.last_},
28 bytes_{that.bytes_}, lastBlockEmpty_{that.lastBlockEmpty_} {
29 that.clear();
30 }
31 CharBuffer &operator=(CharBuffer &&that) {
32 blocks_ = std::move(that.blocks_);
33 last_ = that.last_;
34 bytes_ = that.bytes_;
35 lastBlockEmpty_ = that.lastBlockEmpty_;
36 that.clear();
37 return *this;
38 }
39
40 bool empty() const { return bytes_ == 0; }
41 std::size_t bytes() const { return bytes_; }
42
43 void clear() {
44 blocks_.clear();
45 last_ = blocks_.end();
46 bytes_ = 0;
47 lastBlockEmpty_ = false;
48 }
49
50 char *FreeSpace(std::size_t &);
51 void Claim(std::size_t);
52
53 // The return value is the byte offset of the new data,
54 // i.e. the value of size() before the call.
55 std::size_t Put(const char *data, std::size_t n);
56 std::size_t Put(const std::string &);
57 std::size_t Put(char x) { return Put(&x, 1); }
58
59 std::string Marshal() const;
60
61 private:
62 struct Block {
63 static constexpr std::size_t capacity{1 << 20};
64 char data[capacity];
65 };
66
67 int LastBlockOffset() const { return bytes_ % Block::capacity; }
68 std::forward_list<Block> blocks_;
69 std::forward_list<Block>::iterator last_{blocks_.end()};
70 std::size_t bytes_{0};
71 bool lastBlockEmpty_{false};
72 };
73 } // namespace Fortran::parser
74 #endif // FORTRAN_PARSER_CHAR_BUFFER_H_
Fortran::parser::CharBuffer
Definition: char-buffer.h:23
Fortran::parser
Definition: check-expression.h:19