1 /*
2 * Copyright (c) 2016-present, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 */
9 #include "utils/Buffer.h"
10 #include "utils/Range.h"
11
12 #include <gtest/gtest.h>
13 #include <memory>
14
15 using namespace pzstd;
16
17 namespace {
deleter(const unsigned char * buf)18 void deleter(const unsigned char* buf) {
19 delete[] buf;
20 }
21 }
22
TEST(Buffer,Constructors)23 TEST(Buffer, Constructors) {
24 Buffer empty;
25 EXPECT_TRUE(empty.empty());
26 EXPECT_EQ(0, empty.size());
27
28 Buffer sized(5);
29 EXPECT_FALSE(sized.empty());
30 EXPECT_EQ(5, sized.size());
31
32 Buffer moved(std::move(sized));
33 EXPECT_FALSE(sized.empty());
34 EXPECT_EQ(5, sized.size());
35
36 Buffer assigned;
37 assigned = std::move(moved);
38 EXPECT_FALSE(sized.empty());
39 EXPECT_EQ(5, sized.size());
40 }
41
TEST(Buffer,BufferManagement)42 TEST(Buffer, BufferManagement) {
43 std::shared_ptr<unsigned char> buf(new unsigned char[10], deleter);
44 {
45 Buffer acquired(buf, MutableByteRange(buf.get(), buf.get() + 10));
46 EXPECT_EQ(2, buf.use_count());
47 Buffer moved(std::move(acquired));
48 EXPECT_EQ(2, buf.use_count());
49 Buffer assigned;
50 assigned = std::move(moved);
51 EXPECT_EQ(2, buf.use_count());
52
53 Buffer split = assigned.splitAt(5);
54 EXPECT_EQ(3, buf.use_count());
55
56 split.advance(1);
57 assigned.subtract(1);
58 EXPECT_EQ(3, buf.use_count());
59 }
60 EXPECT_EQ(1, buf.use_count());
61 }
62
TEST(Buffer,Modifiers)63 TEST(Buffer, Modifiers) {
64 Buffer buf(10);
65 {
66 unsigned char i = 0;
67 for (auto& byte : buf.range()) {
68 byte = i++;
69 }
70 }
71
72 auto prefix = buf.splitAt(2);
73
74 ASSERT_EQ(2, prefix.size());
75 EXPECT_EQ(0, *prefix.data());
76
77 ASSERT_EQ(8, buf.size());
78 EXPECT_EQ(2, *buf.data());
79
80 buf.advance(2);
81 EXPECT_EQ(4, *buf.data());
82
83 EXPECT_EQ(9, *(buf.range().end() - 1));
84
85 buf.subtract(2);
86 EXPECT_EQ(7, *(buf.range().end() - 1));
87
88 EXPECT_EQ(4, buf.size());
89 }
90