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