1 /*
2  * Copyright (C) 2017 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 #ifndef AAPT_IO_STRINGSTREAM_H
18 #define AAPT_IO_STRINGSTREAM_H
19 
20 #include <memory>
21 
22 #include "android-base/macros.h"
23 #include "androidfw/Streams.h"
24 #include "androidfw/StringPiece.h"
25 
26 namespace aapt {
27 namespace io {
28 
29 class StringInputStream : public android::KnownSizeInputStream {
30  public:
31   explicit StringInputStream(android::StringPiece str);
32 
33   bool Next(const void** data, size_t* size) override;
34 
35   void BackUp(size_t count) override;
36 
37   size_t ByteCount() const override;
38 
HadError()39   inline bool HadError() const override {
40     return false;
41   }
42 
GetError()43   inline std::string GetError() const override {
44     return {};
45   }
46 
47   size_t TotalSize() const override;
48 
49   bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override;
50 
51  private:
52   DISALLOW_COPY_AND_ASSIGN(StringInputStream);
53 
54   android::StringPiece str_;
55   size_t offset_;
56 };
57 
58 class StringOutputStream : public android::OutputStream {
59  public:
60   explicit StringOutputStream(std::string* str, size_t buffer_capacity = 4096u);
61 
62   ~StringOutputStream();
63 
64   bool Next(void** data, size_t* size) override;
65 
66   void BackUp(size_t count) override;
67 
68   void Flush();
69 
70   size_t ByteCount() const override;
71 
HadError()72   inline bool HadError() const override {
73     return false;
74   }
75 
GetError()76   inline std::string GetError() const override {
77     return {};
78   }
79 
80  private:
81   DISALLOW_COPY_AND_ASSIGN(StringOutputStream);
82 
83   void FlushImpl();
84 
85   std::string* str_;
86   size_t buffer_capacity_;
87   size_t buffer_offset_;
88   std::unique_ptr<char[]> buffer_;
89 };
90 
91 }  // namespace io
92 }  // namespace aapt
93 
94 #endif  // AAPT_IO_STRINGSTREAM_H
95