summaryrefslogtreecommitdiff
path: root/src/cbor/cbor_encoder.cpp
blob: 863597b4f6927a79983bfe5e40a27a7f45367c53 (plain)
1
2
3
4
5
6
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
#include "cbor_encoder.hpp"
#include <cstdint>
#include "esp-idf/components/cbor/tinycbor/src/cbor.h"

namespace cbor {

  static const int kEncoderFlags = 0;

Encoder::Encoder(ContainerType type, uint32_t container_len, uint8_t *buffer, size_t buffer_len) {
  cbor_encoder_init(&root_encoder, buffer, buffer_len, kEncoderFlags);
  switch (type) {
    case CONTAINER_ARRAY:
      error_ = cbor_encoder_create_array(&encoder, &container_encoder_, container_len);
      break;
    case CONTAINER_MAP:
      error_ = cbor_encoder_create_map(&encoder, &container_encoder_, container_len);
      break;
  }
}

auto Encoder::WriteString(const std::string &val) -> void {
  if (error_ != CborNoError) {
    return;
  }
  error_ = cbor_encode_byte_string(&container_encoder_, val.c_str(), val.size());
}

auto Encoder::WriteUnsigned(uint32_t val) -> void {
  if (error_ != CborNoError) {
    return;
  }
  error_ = cbor_encode_uint(&container_encoder_, val);
}

auto Encoder::WriteSigned(int32_t val) -> void {
  if (error_ != CborNoError) {
    return;
  }
  error_ = cbor_encode_int(&container_encoder_, val);
}

auto Encoder::Finish() -> cpp::result<size_t, CborError> {
  if (error_ != CborNoError) {
    return cpp::fail(error_);
  }
  if (CborError final_error = cbor_encoder_close_container(&root_encoder, &container_encoder_) != CborNoError) {
    return cpp::fail(final_error);
  }
  return cbor_encoder_get_buffer_size(&root_encoder);
}

} // namespace cbor