• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "buffered_output_stream.h"
18 
19 #include <string.h>
20 
21 namespace art {
22 namespace linker {
23 
BufferedOutputStream(std::unique_ptr<OutputStream> out)24 BufferedOutputStream::BufferedOutputStream(std::unique_ptr<OutputStream> out)
25     : OutputStream(out->GetLocation()),  // Before out is moved to out_.
26       out_(std::move(out)),
27       used_(0) {}
28 
~BufferedOutputStream()29 BufferedOutputStream::~BufferedOutputStream() {
30   FlushBuffer();
31 }
32 
WriteFully(const void * buffer,size_t byte_count)33 bool BufferedOutputStream::WriteFully(const void* buffer, size_t byte_count) {
34   if (byte_count > kBufferSize) {
35     if (!FlushBuffer()) {
36       return false;
37     }
38     return out_->WriteFully(buffer, byte_count);
39   }
40   if (used_ + byte_count > kBufferSize) {
41     if (!FlushBuffer()) {
42       return false;
43     }
44   }
45   const uint8_t* src = reinterpret_cast<const uint8_t*>(buffer);
46   memcpy(&buffer_[used_], src, byte_count);
47   used_ += byte_count;
48   return true;
49 }
50 
Flush()51 bool BufferedOutputStream::Flush() {
52   return FlushBuffer() && out_->Flush();
53 }
54 
FlushBuffer()55 bool BufferedOutputStream::FlushBuffer() {
56   bool success = true;
57   if (used_ > 0) {
58     success = out_->WriteFully(&buffer_[0], used_);
59     used_ = 0;
60   }
61   return success;
62 }
63 
Seek(off_t offset,Whence whence)64 off_t BufferedOutputStream::Seek(off_t offset, Whence whence) {
65   if (!FlushBuffer()) {
66     return -1;
67   }
68   return out_->Seek(offset, whence);
69 }
70 
71 }  // namespace linker
72 }  // namespace art
73