test_byte_buffer.cpp 2.32 KB
Newer Older
1
2
3
4
5
6
7
8
/*!
 * Copyright (c) 2022 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */

#include <gtest/gtest.h>
#include <LightGBM/utils/byte_buffer.h>

9
#include <memory>
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <random>

using LightGBM::ByteBuffer;


TEST(ByteBuffer, JustWorks) {
  std::unique_ptr<ByteBuffer> buffer;
  buffer.reset(new ByteBuffer());

  int cumulativeSize = 0;
  EXPECT_EQ(cumulativeSize, buffer->GetSize());

  int8_t int8Val = 34;
  cumulativeSize += sizeof(int8_t);
  buffer->Write(&int8Val, sizeof(int8_t));
  EXPECT_EQ(cumulativeSize, buffer->GetSize());
  EXPECT_EQ(int8Val, buffer->GetAt(cumulativeSize - 1));

  int16_t int16Val = 33;
  cumulativeSize += sizeof(int16_t);
  buffer->Write(&int16Val, sizeof(int16_t));
  EXPECT_EQ(cumulativeSize, buffer->GetSize());
  int16_t serializedInt16 = 0;
  char* int16Ptr = reinterpret_cast<char*>(&serializedInt16);
34
  for (unsigned int i = 0; i < sizeof(int16_t); i++) {
35
36
37
38
39
40
41
42
43
44
    int16Ptr[i] = buffer->GetAt(cumulativeSize - (sizeof(int16_t) - i));
  }
  EXPECT_EQ(int16Val, serializedInt16);

  int64_t int64Val = 35;
  cumulativeSize += sizeof(int64_t);
  buffer->Write(&int64Val, sizeof(int64_t));
  EXPECT_EQ(cumulativeSize, buffer->GetSize());
  int64_t serializedInt64 = 0;
  char* int64Ptr = reinterpret_cast<char*>(&serializedInt64);
45
  for (unsigned int i = 0; i < sizeof(int64_t); i++) {
46
47
48
49
50
51
52
53
54
55
    int64Ptr[i] = buffer->GetAt(cumulativeSize - (sizeof(int64_t) - i));
  }
  EXPECT_EQ(int64Val, serializedInt64);

  double doubleVal = 36.6;
  cumulativeSize += sizeof(double);
  buffer->Write(&doubleVal, sizeof(doubleVal));
  EXPECT_EQ(cumulativeSize, buffer->GetSize());
  double serializedDouble = 0;
  char* doublePtr = reinterpret_cast<char*>(&serializedDouble);
56
  for (unsigned int i = 0; i < sizeof(double); i++) {
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    doublePtr[i] = buffer->GetAt(cumulativeSize - (sizeof(double) - i));
  }
  EXPECT_EQ(doubleVal, serializedDouble);

  const int charSize = 3;
  char charArrayVal[charSize] = { 'a', 'b', 'c' };
  cumulativeSize += charSize;
  buffer->Write(charArrayVal, charSize);
  EXPECT_EQ(cumulativeSize, buffer->GetSize());
  for (int i = 0; i < charSize; i++) {
    EXPECT_EQ(charArrayVal[i], buffer->GetAt(cumulativeSize - (charSize - i)));
  }

  // Test that Data() points to first value written
  EXPECT_EQ(int8Val, *buffer->Data());
}