1 // Copyright 2019 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 "aemu/base/files/MemStream.h"
16
17 #include "aemu/base/files/StreamSerializing.h"
18
19 #include <algorithm>
20 #include <utility>
21
22 #include <string.h>
23
24 namespace android {
25 namespace base {
26
MemStream(int reserveSize)27 MemStream::MemStream(int reserveSize) {
28 mData.reserve(reserveSize);
29 }
30
MemStream(Buffer && data)31 MemStream::MemStream(Buffer&& data) : mData(std::move(data)) {}
32
read(void * buffer,size_t size)33 ssize_t MemStream::read(void* buffer, size_t size) {
34 if (!buffer) {
35 return 0;
36 }
37 const auto sizeToRead = std::min<int>(size, readSize());
38 memcpy(buffer, mData.data() + mReadPos, sizeToRead);
39 mReadPos += sizeToRead;
40 return sizeToRead;
41 }
42
write(const void * buffer,size_t size)43 ssize_t MemStream::write(const void* buffer, size_t size) {
44 if (!buffer) {
45 return 0;
46 }
47 mData.insert(mData.end(), (const char*)buffer, (const char*)buffer + size);
48 return size;
49 }
50
writtenSize() const51 int MemStream::writtenSize() const {
52 return (int)mData.size();
53 }
54
readPos() const55 int MemStream::readPos() const {
56 return mReadPos;
57 }
58
readSize() const59 int MemStream::readSize() const {
60 return mData.size() - mReadPos;
61 }
62
save(Stream * stream) const63 void MemStream::save(Stream* stream) const {
64 saveBuffer(stream, mData);
65 }
66
load(Stream * stream)67 void MemStream::load(Stream* stream) {
68 loadBuffer(stream, &mData);
69 mReadPos = 0;
70 }
71
rewind()72 void MemStream::rewind() {
73 mReadPos = 0;
74 }
75
76 } // namespace base
77 } // namespace android
78