Home | History | Annotate | Download | only in files
      1 // Copyright 2015 The Android Open Source Project
      2 //
      3 // This software is licensed under the terms of the GNU General Public
      4 // License version 2, as published by the Free Software Foundation, and
      5 // may be copied, distributed, and modified under those terms.
      6 //
      7 // This program is distributed in the hope that it will be useful,
      8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
      9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     10 // GNU General Public License for more details.
     11 
     12 #include "android/base/files/MemStream.h"
     13 
     14 #include "android/base/files/StreamSerializing.h"
     15 
     16 #include <algorithm>
     17 #include <utility>
     18 
     19 namespace android {
     20 namespace base {
     21 
     22 MemStream::MemStream(int reserveSize) {
     23     mData.reserve(reserveSize);
     24 }
     25 
     26 MemStream::MemStream(Buffer&& data) : mData(std::move(data)) {}
     27 
     28 ssize_t MemStream::read(void* buffer, size_t size) {
     29     const auto sizeToRead = std::min<int>(size, readSize());
     30     memcpy(buffer, mData.data() + mReadPos, sizeToRead);
     31     mReadPos += sizeToRead;
     32     return sizeToRead;
     33 }
     34 
     35 ssize_t MemStream::write(const void* buffer, size_t size) {
     36     mData.insert(mData.end(), (const char*)buffer, (const char*)buffer + size);
     37     return size;
     38 }
     39 
     40 int MemStream::writtenSize() const {
     41     return (int)mData.size();
     42 }
     43 
     44 int MemStream::readPos() const {
     45     return mReadPos;
     46 }
     47 
     48 int MemStream::readSize() const {
     49     return mData.size() - mReadPos;
     50 }
     51 
     52 void MemStream::save(Stream* stream) const {
     53     saveBuffer(stream, mData);
     54 }
     55 
     56 void MemStream::load(Stream* stream) {
     57     loadBuffer(stream, &mData);
     58     mReadPos = 0;
     59 }
     60 
     61 }  // namespace base
     62 }  // namespace android
     63