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