1 /*
2 * Copyright (C) 2017 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 "src/protozero/test/fake_scattered_buffer.h"
18
19 #include <iomanip>
20 #include <sstream>
21 #include <utility>
22
23 #include "test/gtest_and_gmock.h"
24
25 namespace protozero {
26
27 namespace {
28
ToHex(const void * data,size_t length)29 std::string ToHex(const void* data, size_t length) {
30 std::ostringstream ss;
31 ss << std::hex << std::setfill('0');
32 ss << std::uppercase;
33 for (size_t i = 0; i < length; i++) {
34 char c = reinterpret_cast<const char*>(data)[i];
35 ss << std::setw(2) << (static_cast<unsigned>(c) & 0xFF);
36 }
37 return ss.str();
38 }
39
40 } // namespace
41
FakeScatteredBuffer(size_t chunk_size)42 FakeScatteredBuffer::FakeScatteredBuffer(size_t chunk_size)
43 : chunk_size_(chunk_size) {}
44
~FakeScatteredBuffer()45 FakeScatteredBuffer::~FakeScatteredBuffer() {}
46
GetNewBuffer()47 ContiguousMemoryRange FakeScatteredBuffer::GetNewBuffer() {
48 std::unique_ptr<uint8_t[]> chunk(new uint8_t[chunk_size_]);
49 uint8_t* begin = chunk.get();
50 memset(begin, 0, chunk_size_);
51 chunks_.push_back(std::move(chunk));
52 return {begin, begin + chunk_size_};
53 }
54
GetChunkAsString(size_t chunk_index)55 std::string FakeScatteredBuffer::GetChunkAsString(size_t chunk_index) {
56 return ToHex(chunks_[chunk_index].get(), chunk_size_);
57 }
58
GetBytes(size_t start,size_t length,uint8_t * buf)59 void FakeScatteredBuffer::GetBytes(size_t start, size_t length, uint8_t* buf) {
60 ASSERT_LE(start + length, chunks_.size() * chunk_size_);
61 for (size_t pos = 0; pos < length; ++pos) {
62 size_t chunk_index = (start + pos) / chunk_size_;
63 size_t chunk_offset = (start + pos) % chunk_size_;
64 buf[pos] = chunks_[chunk_index].get()[chunk_offset];
65 }
66 }
67
GetBytesAsString(size_t start,size_t length)68 std::string FakeScatteredBuffer::GetBytesAsString(size_t start, size_t length) {
69 std::unique_ptr<uint8_t[]> buffer(new uint8_t[length]);
70 GetBytes(start, length, buffer.get());
71 return ToHex(buffer.get(), length);
72 }
73
74 } // namespace protozero
75