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 #include "io/StringStream.h"
18 
19 using ::android::StringPiece;
20 
21 namespace aapt {
22 namespace io {
23 
StringInputStream(const StringPiece & str)24 StringInputStream::StringInputStream(const StringPiece& str) : str_(str), offset_(0u) {
25 }
26 
Next(const void ** data,size_t * size)27 bool StringInputStream::Next(const void** data, size_t* size) {
28   if (offset_ == str_.size()) {
29     return false;
30   }
31 
32   *data = str_.data() + offset_;
33   *size = str_.size() - offset_;
34   offset_ = str_.size();
35   return true;
36 }
37 
BackUp(size_t count)38 void StringInputStream::BackUp(size_t count) {
39   if (count > offset_) {
40     offset_ = 0u;
41   } else {
42     offset_ -= count;
43   }
44 }
45 
ByteCount() const46 size_t StringInputStream::ByteCount() const {
47   return offset_;
48 }
49 
TotalSize() const50 size_t StringInputStream::TotalSize() const {
51   return str_.size();
52 }
53 
StringOutputStream(std::string * str,size_t buffer_capacity)54 StringOutputStream::StringOutputStream(std::string* str, size_t buffer_capacity)
55     : str_(str),
56       buffer_capacity_(buffer_capacity),
57       buffer_offset_(0u),
58       buffer_(new char[buffer_capacity]) {
59 }
60 
~StringOutputStream()61 StringOutputStream::~StringOutputStream() {
62   Flush();
63 }
64 
Next(void ** data,size_t * size)65 bool StringOutputStream::Next(void** data, size_t* size) {
66   if (buffer_offset_ == buffer_capacity_) {
67     FlushImpl();
68   }
69 
70   *data = buffer_.get() + buffer_offset_;
71   *size = buffer_capacity_ - buffer_offset_;
72   buffer_offset_ = buffer_capacity_;
73   return true;
74 }
75 
BackUp(size_t count)76 void StringOutputStream::BackUp(size_t count) {
77   if (count > buffer_offset_) {
78     buffer_offset_ = 0u;
79   } else {
80     buffer_offset_ -= count;
81   }
82 }
83 
ByteCount() const84 size_t StringOutputStream::ByteCount() const {
85   return str_->size() + buffer_offset_;
86 }
87 
Flush()88 void StringOutputStream::Flush() {
89   if (buffer_offset_ != 0u) {
90     FlushImpl();
91   }
92 }
93 
FlushImpl()94 void StringOutputStream::FlushImpl() {
95   str_->append(buffer_.get(), buffer_offset_);
96   buffer_offset_ = 0u;
97 }
98 
99 }  // namespace io
100 }  // namespace aapt
101