1 // Copyright 2015 The Chromium OS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "buffer_writer.h" 6 7 #include <string.h> 8 9 #include <algorithm> 10 11 namespace quipper { 12 13 bool BufferWriter::WriteData(const void* src, const size_t size) { 14 // Do not write anything if the write needs to be truncated to avoid writing 15 // past the end of the file. The extra conditions here are in case of integer 16 // overflow. 17 if (offset_ + size > size_ || offset_ >= size_ || size > size_) return false; 18 memcpy(buffer_ + offset_, src, size); 19 offset_ += size; 20 return true; 21 } 22 23 bool BufferWriter::WriteString(const string& str, const size_t size) { 24 // Make sure there is enough space left in the buffer. 25 size_t write_size = std::min(str.size(), size); 26 if (offset_ + size > size_ || !WriteData(str.c_str(), write_size)) 27 return false; 28 29 // Write the padding, if any. Note that the offset has been updated by 30 // WriteData. 31 memset(buffer_ + offset_, 0, size - write_size); 32 offset_ += size - write_size; 33 return true; 34 } 35 36 bool BufferWriter::CanWriteSize(size_t data_size) { 37 return Tell() + data_size <= size(); 38 } 39 40 } // namespace quipper 41