1 // Copyright (c) 2012 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 "remoting/base/typed_buffer.h" 6 #include "testing/gtest/include/gtest/gtest.h" 7 8 namespace remoting { 9 10 namespace { 11 12 struct Data { 13 // A variable size vector. 14 int data[1]; 15 }; 16 17 } // namespace 18 19 // Check that the default constructor does not allocate the buffer. 20 TEST(TypedBufferTest, Empty) { 21 TypedBuffer<Data> buffer; 22 EXPECT_FALSE(buffer.get()); 23 EXPECT_FALSE(buffer); 24 EXPECT_EQ(buffer.length(), 0u); 25 } 26 27 // Check that allocating zero-size structure does not allocate the buffer. 28 TEST(TypedBufferTest, ZeroSize) { 29 TypedBuffer<Data> buffer(0); 30 EXPECT_FALSE(buffer.get()); 31 EXPECT_FALSE(buffer); 32 EXPECT_EQ(buffer.length(), 0u); 33 } 34 35 // Test creation of a buffer and verify that the buffer accessors work. 36 TEST(TypedBufferTest, Basic) { 37 TypedBuffer<Data> buffer(sizeof(int) * 10); 38 EXPECT_TRUE(buffer.get()); 39 EXPECT_TRUE(buffer); 40 EXPECT_EQ(buffer.length(), sizeof(int) * 10); 41 42 // Make sure that operator*() syntax works. 43 (*buffer).data[9] = 0x12345678; 44 45 // Make sure that operator->() syntax works. 46 EXPECT_EQ(buffer->data[9], 0x12345678); 47 } 48 49 // Test passing ownership. 50 TEST(TypedBufferTest, Pass) { 51 TypedBuffer<Data> left; 52 TypedBuffer<Data> right(sizeof(int)); 53 54 EXPECT_FALSE(left.get()); 55 EXPECT_EQ(left.length(), 0u); 56 EXPECT_TRUE(right.get()); 57 EXPECT_EQ(right.length(), sizeof(int)); 58 59 Data* raw_ptr = right.get(); 60 left = right.Pass(); 61 62 // Verify that passing ownership transfers both the buffer pointer and its 63 // length. 64 EXPECT_EQ(left.get(), raw_ptr); 65 EXPECT_EQ(left.length(), sizeof(int)); 66 67 // Verify that the original object was cleared. 68 EXPECT_FALSE(right.get()); 69 EXPECT_EQ(right.length(), 0u); 70 } 71 72 // Test swapping ownership. 73 TEST(TypedBufferTest, Swap) { 74 TypedBuffer<Data> left(sizeof(int)); 75 TypedBuffer<Data> right(sizeof(int) * 2); 76 77 EXPECT_TRUE(left.get()); 78 EXPECT_EQ(left.length(), sizeof(int)); 79 EXPECT_TRUE(right.get()); 80 EXPECT_EQ(right.length(), sizeof(int) * 2); 81 82 Data* raw_left = left.get(); 83 Data* raw_right = right.get(); 84 left.Swap(right); 85 86 // Verify that swapping simply exchange contents of two objects. 87 // length. 88 EXPECT_EQ(left.get(), raw_right); 89 EXPECT_EQ(left.length(), sizeof(int) * 2); 90 EXPECT_EQ(right.get(), raw_left); 91 EXPECT_EQ(right.length(), sizeof(int)); 92 } 93 94 TEST(TypedBufferTest, GetAtOffset) { 95 TypedBuffer<Data> buffer(sizeof(int) * 10); 96 EXPECT_EQ(buffer.get(), buffer.GetAtOffset(0)); 97 EXPECT_EQ(reinterpret_cast<Data*>(&buffer->data[9]), 98 buffer.GetAtOffset(sizeof(int) * 9)); 99 } 100 101 } // namespace remoting 102