1 /*
2  * Copyright (C) 2013 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 ART_COMPILER_LINKER_VECTOR_OUTPUT_STREAM_H_
18 #define ART_COMPILER_LINKER_VECTOR_OUTPUT_STREAM_H_
19 
20 #include "output_stream.h"
21 
22 #include <string.h>
23 #include <string>
24 #include <vector>
25 
26 namespace art {
27 namespace linker {
28 
29 class VectorOutputStream FINAL : public OutputStream {
30  public:
31   VectorOutputStream(const std::string& location, std::vector<uint8_t>* vector);
32 
~VectorOutputStream()33   ~VectorOutputStream() OVERRIDE {}
34 
WriteFully(const void * buffer,size_t byte_count)35   bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
36     if (static_cast<size_t>(offset_) == vector_->size()) {
37       const uint8_t* start = reinterpret_cast<const uint8_t*>(buffer);
38       vector_->insert(vector_->end(), &start[0], &start[byte_count]);
39       offset_ += byte_count;
40     } else {
41       off_t new_offset = offset_ + byte_count;
42       EnsureCapacity(new_offset);
43       memcpy(&(*vector_)[offset_], buffer, byte_count);
44       offset_ = new_offset;
45     }
46     return true;
47   }
48 
49   off_t Seek(off_t offset, Whence whence) OVERRIDE;
50 
Flush()51   bool Flush() OVERRIDE {
52     return true;
53   }
54 
55  private:
EnsureCapacity(off_t new_offset)56   void EnsureCapacity(off_t new_offset) {
57     if (new_offset > static_cast<off_t>(vector_->size())) {
58       vector_->resize(new_offset);
59     }
60   }
61 
62   off_t offset_;
63   std::vector<uint8_t>* const vector_;
64 
65   DISALLOW_COPY_AND_ASSIGN(VectorOutputStream);
66 };
67 
68 }  // namespace linker
69 }  // namespace art
70 
71 #endif  // ART_COMPILER_LINKER_VECTOR_OUTPUT_STREAM_H_
72