1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/memory/ref_counted_memory.h"
6
7#include "testing/gtest/include/gtest/gtest.h"
8
9namespace base {
10
11TEST(RefCountedMemoryUnitTest, RefCountedStaticMemory) {
12  scoped_refptr<RefCountedMemory> mem = new RefCountedStaticMemory(
13      "static mem00", 10);
14
15  EXPECT_EQ(10U, mem->size());
16  EXPECT_EQ("static mem", std::string(mem->front_as<char>(), mem->size()));
17}
18
19TEST(RefCountedMemoryUnitTest, RefCountedBytes) {
20  std::vector<uint8> data;
21  data.push_back(45);
22  data.push_back(99);
23  scoped_refptr<RefCountedMemory> mem = RefCountedBytes::TakeVector(&data);
24
25  EXPECT_EQ(0U, data.size());
26
27  EXPECT_EQ(2U, mem->size());
28  EXPECT_EQ(45U, mem->front()[0]);
29  EXPECT_EQ(99U, mem->front()[1]);
30
31  scoped_refptr<RefCountedMemory> mem2;
32  {
33    unsigned char data2[] = { 12, 11, 99 };
34    mem2 = new RefCountedBytes(data2, 3);
35  }
36  EXPECT_EQ(3U, mem2->size());
37  EXPECT_EQ(12U, mem2->front()[0]);
38  EXPECT_EQ(11U, mem2->front()[1]);
39  EXPECT_EQ(99U, mem2->front()[2]);
40}
41
42TEST(RefCountedMemoryUnitTest, RefCountedString) {
43  std::string s("destroy me");
44  scoped_refptr<RefCountedMemory> mem = RefCountedString::TakeString(&s);
45
46  EXPECT_EQ(0U, s.size());
47
48  EXPECT_EQ(10U, mem->size());
49  EXPECT_EQ('d', mem->front()[0]);
50  EXPECT_EQ('e', mem->front()[1]);
51}
52
53TEST(RefCountedMemoryUnitTest, RefCountedMallocedMemory) {
54  void* data = malloc(6);
55  memcpy(data, "hello", 6);
56
57  scoped_refptr<RefCountedMemory> mem = new RefCountedMallocedMemory(data, 6);
58
59  EXPECT_EQ(6U, mem->size());
60  EXPECT_EQ(0, memcmp("hello", mem->front(), 6));
61}
62
63TEST(RefCountedMemoryUnitTest, Equals) {
64  std::string s1("same");
65  scoped_refptr<RefCountedMemory> mem1 = RefCountedString::TakeString(&s1);
66
67  std::vector<unsigned char> d2;
68  d2.push_back('s');
69  d2.push_back('a');
70  d2.push_back('m');
71  d2.push_back('e');
72  scoped_refptr<RefCountedMemory> mem2 = RefCountedBytes::TakeVector(&d2);
73
74  EXPECT_TRUE(mem1->Equals(mem2));
75
76  std::string s3("diff");
77  scoped_refptr<RefCountedMemory> mem3 = RefCountedString::TakeString(&s3);
78
79  EXPECT_FALSE(mem1->Equals(mem3));
80  EXPECT_FALSE(mem2->Equals(mem3));
81}
82
83TEST(RefCountedMemoryUnitTest, EqualsNull) {
84  std::string s("str");
85  scoped_refptr<RefCountedMemory> mem = RefCountedString::TakeString(&s);
86  EXPECT_FALSE(mem->Equals(NULL));
87}
88
89}  //  namespace base
90