byte_buffer.h 1.37 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2022 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
5
6
#ifndef LIGHTGBM_INCLUDE_LIGHTGBM_UTILS_BYTE_BUFFER_H_
#define LIGHTGBM_INCLUDE_LIGHTGBM_UTILS_BYTE_BUFFER_H_
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

#include <LightGBM/export.h>
#include <LightGBM/utils/binary_writer.h>

#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>

namespace LightGBM {

/*!
  * \brief An implementation for serializing binary data to an auto-expanding memory buffer
  */
struct ByteBuffer final : public BinaryWriter {
  ByteBuffer() {}

  explicit ByteBuffer(size_t initial_size) {
    buffer_.reserve(initial_size);
  }

  size_t Write(const void* data, size_t bytes) {
    const char* mem_ptr = static_cast<const char*>(data);
    for (size_t i = 0; i < bytes; ++i) {
      buffer_.push_back(mem_ptr[i]);
    }

    return bytes;
  }

  LIGHTGBM_EXPORT void Reserve(size_t capacity) {
    buffer_.reserve(capacity);
  }

  LIGHTGBM_EXPORT size_t GetSize() {
    return buffer_.size();
  }

  LIGHTGBM_EXPORT char GetAt(size_t index) {
    return buffer_.at(index);
  }

  LIGHTGBM_EXPORT char* Data() {
    return buffer_.data();
  }

 private:
  std::vector<char> buffer_;
};

}  // namespace LightGBM

62
#endif   // LIGHTGBM_INCLUDE_LIGHTGBM_UTILS_BYTE_BUFFER_H_