blob: af3d6b9aeab13e226d47fb710aaecebbba3afb79 [file] [log] [blame]
Christopher Ferrisf447c8e2017-04-03 12:39:47 -07001/*
2 * Copyright (C) 2016 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 <vector>
18
19#include <gtest/gtest.h>
20
21#include "Memory.h"
22
23#include "LogFake.h"
24
25class MemoryBufferTest : public ::testing::Test {
26 protected:
27 void SetUp() override {
28 ResetLogs();
29 memory_.reset(new MemoryBuffer);
30 }
31 std::unique_ptr<MemoryBuffer> memory_;
32};
33
34TEST_F(MemoryBufferTest, empty) {
35 ASSERT_EQ(0U, memory_->Size());
36 std::vector<uint8_t> buffer(1024);
37 ASSERT_FALSE(memory_->Read(0, buffer.data(), 1));
38 ASSERT_EQ(nullptr, memory_->GetPtr(0));
39 ASSERT_EQ(nullptr, memory_->GetPtr(1));
40}
41
42TEST_F(MemoryBufferTest, write_read) {
43 memory_->Resize(256);
44 ASSERT_EQ(256U, memory_->Size());
45 ASSERT_TRUE(memory_->GetPtr(0) != nullptr);
46 ASSERT_TRUE(memory_->GetPtr(1) != nullptr);
47 ASSERT_TRUE(memory_->GetPtr(255) != nullptr);
48 ASSERT_TRUE(memory_->GetPtr(256) == nullptr);
49
50 uint8_t* data = memory_->GetPtr(0);
51 for (size_t i = 0; i < memory_->Size(); i++) {
52 data[i] = i;
53 }
54
55 std::vector<uint8_t> buffer(memory_->Size());
56 ASSERT_TRUE(memory_->Read(0, buffer.data(), buffer.size()));
57 for (size_t i = 0; i < buffer.size(); i++) {
58 ASSERT_EQ(i, buffer[i]) << "Failed at byte " << i;
59 }
60}
61
62TEST_F(MemoryBufferTest, read_failures) {
63 memory_->Resize(100);
64 std::vector<uint8_t> buffer(200);
65 ASSERT_FALSE(memory_->Read(0, buffer.data(), 101));
66 ASSERT_FALSE(memory_->Read(100, buffer.data(), 1));
67 ASSERT_FALSE(memory_->Read(101, buffer.data(), 2));
68 ASSERT_FALSE(memory_->Read(99, buffer.data(), 2));
69 ASSERT_TRUE(memory_->Read(99, buffer.data(), 1));
70}
71
72TEST_F(MemoryBufferTest, read_failure_overflow) {
73 memory_->Resize(100);
74 std::vector<uint8_t> buffer(200);
75
76 ASSERT_FALSE(memory_->Read(UINT64_MAX - 100, buffer.data(), 200));
77}