ref_counted_memory_unittest.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. #include "butil/memory/ref_counted_memory.h"
  5. #include <gtest/gtest.h>
  6. namespace butil {
  7. TEST(RefCountedMemoryUnitTest, RefCountedStaticMemory) {
  8. scoped_refptr<RefCountedMemory> mem = new RefCountedStaticMemory(
  9. "static mem00", 10);
  10. EXPECT_EQ(10U, mem->size());
  11. EXPECT_EQ("static mem", std::string(mem->front_as<char>(), mem->size()));
  12. }
  13. TEST(RefCountedMemoryUnitTest, RefCountedBytes) {
  14. std::vector<uint8_t> data;
  15. data.push_back(45);
  16. data.push_back(99);
  17. scoped_refptr<RefCountedMemory> mem = RefCountedBytes::TakeVector(&data);
  18. EXPECT_EQ(0U, data.size());
  19. EXPECT_EQ(2U, mem->size());
  20. EXPECT_EQ(45U, mem->front()[0]);
  21. EXPECT_EQ(99U, mem->front()[1]);
  22. scoped_refptr<RefCountedMemory> mem2;
  23. {
  24. unsigned char data2[] = { 12, 11, 99 };
  25. mem2 = new RefCountedBytes(data2, 3);
  26. }
  27. EXPECT_EQ(3U, mem2->size());
  28. EXPECT_EQ(12U, mem2->front()[0]);
  29. EXPECT_EQ(11U, mem2->front()[1]);
  30. EXPECT_EQ(99U, mem2->front()[2]);
  31. }
  32. TEST(RefCountedMemoryUnitTest, RefCountedString) {
  33. std::string s("destroy me");
  34. scoped_refptr<RefCountedMemory> mem = RefCountedString::TakeString(&s);
  35. EXPECT_EQ(0U, s.size());
  36. EXPECT_EQ(10U, mem->size());
  37. EXPECT_EQ('d', mem->front()[0]);
  38. EXPECT_EQ('e', mem->front()[1]);
  39. }
  40. TEST(RefCountedMemoryUnitTest, RefCountedMallocedMemory) {
  41. void* data = malloc(6);
  42. memcpy(data, "hello", 6);
  43. scoped_refptr<RefCountedMemory> mem = new RefCountedMallocedMemory(data, 6);
  44. EXPECT_EQ(6U, mem->size());
  45. EXPECT_EQ(0, memcmp("hello", mem->front(), 6));
  46. }
  47. TEST(RefCountedMemoryUnitTest, Equals) {
  48. std::string s1("same");
  49. scoped_refptr<RefCountedMemory> mem1 = RefCountedString::TakeString(&s1);
  50. std::vector<unsigned char> d2;
  51. d2.push_back('s');
  52. d2.push_back('a');
  53. d2.push_back('m');
  54. d2.push_back('e');
  55. scoped_refptr<RefCountedMemory> mem2 = RefCountedBytes::TakeVector(&d2);
  56. EXPECT_TRUE(mem1->Equals(mem2));
  57. std::string s3("diff");
  58. scoped_refptr<RefCountedMemory> mem3 = RefCountedString::TakeString(&s3);
  59. EXPECT_FALSE(mem1->Equals(mem3));
  60. EXPECT_FALSE(mem2->Equals(mem3));
  61. }
  62. TEST(RefCountedMemoryUnitTest, EqualsNull) {
  63. std::string s("str");
  64. scoped_refptr<RefCountedMemory> mem = RefCountedString::TakeString(&s);
  65. EXPECT_FALSE(mem->Equals(NULL));
  66. }
  67. } // namespace butil