• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 #include <stdio.h>
20 
21 #include <functional>
22 #include <memory>
23 #include <ostream>
24 #include <string>
25 #include <utility>
26 
27 #include <android-base/stringprintf.h>
28 
29 namespace android {
30 namespace aidl {
31 
32 class CodeWriter;
33 using CodeWriterPtr = std::unique_ptr<CodeWriter>;
34 
35 class CodeWriter {
36  public:
37   // Get a CodeWriter that writes to a file. When filename is "-",
38   // it is written to stdout.
39   static CodeWriterPtr ForFile(const std::string& filename);
40   // Get a CodeWriter that writes to a string buffer.
41   // The buffer gets updated only after Close() is called or the CodeWriter
42   // is deleted -- much like a real file.
43   static CodeWriterPtr ForString(std::string* buf);
44   // Write a formatted string to this writer in the usual printf sense.
45   // Returns false on error.
46   template <typename... Args>
Write(const char * format,Args...args)47   bool Write(const char* format, Args... args) __attribute__((format(printf, 2, 0))) {
48     std::string formatted;
49     android::base::StringAppendF(&formatted, format, args...);
50 
51     return WriteString(formatted);
52   }
53 
54   template <>
Write(const char * str)55   bool Write(const char* str) {
56     return WriteString(str);
57   }
58 
59   virtual bool WriteString(const std::string&);
60 
61   void Indent();
62   void Dedent();
63   virtual bool Close();
64   virtual ~CodeWriter() = default;
65   CodeWriter() = default;
66 
67   CodeWriter& operator<<(const char* s);
68   CodeWriter& operator<<(const std::string& str);
69 
70  private:
71   CodeWriter(std::unique_ptr<std::ostream> ostream);
72   std::string ApplyIndent(const std::string& str);
73   const std::unique_ptr<std::ostream> ostream_;
74   int indent_level_ {0};
75   bool start_of_line_ {true};
76 };
77 
78 std::string QuotedEscape(const std::string& str);
79 
80 }  // namespace aidl
81 }  // namespace android
82