1 // Copyright 2015 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "android/base/files/MemStream.h"
16 
17 #include "android/base/files/StreamSerializing.h"
18 
19 #include <algorithm>
20 #include <utility>
21 
22 namespace android {
23 namespace base {
24 
MemStream(int reserveSize)25 MemStream::MemStream(int reserveSize) {
26     mData.reserve(reserveSize);
27 }
28 
MemStream(Buffer && data)29 MemStream::MemStream(Buffer&& data) : mData(std::move(data)) {}
30 
read(void * buffer,size_t size)31 ssize_t MemStream::read(void* buffer, size_t size) {
32     const auto sizeToRead = std::min<int>(size, readSize());
33     memcpy(buffer, mData.data() + mReadPos, sizeToRead);
34     mReadPos += sizeToRead;
35     return sizeToRead;
36 }
37 
write(const void * buffer,size_t size)38 ssize_t MemStream::write(const void* buffer, size_t size) {
39     mData.insert(mData.end(), (const char*)buffer, (const char*)buffer + size);
40     return size;
41 }
42 
writtenSize() const43 int MemStream::writtenSize() const {
44     return (int)mData.size();
45 }
46 
readPos() const47 int MemStream::readPos() const {
48     return mReadPos;
49 }
50 
readSize() const51 int MemStream::readSize() const {
52     return mData.size() - mReadPos;
53 }
54 
save(Stream * stream) const55 void MemStream::save(Stream* stream) const {
56     saveBuffer(stream, mData);
57 }
58 
load(Stream * stream)59 void MemStream::load(Stream* stream) {
60     loadBuffer(stream, &mData);
61     mReadPos = 0;
62 }
63 
64 }  // namespace base
65 }  // namespace android
66