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