hyperledger/iroha
Iroha - A simple, decentralized ledger http://iroha.tech
blob.hpp
Go to the documentation of this file.
1 
6 #ifndef IROHA_COMMON_BLOB_HPP
7 #define IROHA_COMMON_BLOB_HPP
8 
9 #include <algorithm>
10 #include <array>
11 #include <cstdint>
12 #include <stdexcept>
13 #include <string>
14 
15 #include "common/hexutils.hpp"
16 
17 namespace iroha {
18  using BadFormatException = std::invalid_argument;
19  using byte_t = uint8_t;
20 
21  namespace {
22  static const std::string code = {'0',
23  '1',
24  '2',
25  '3',
26  '4',
27  '5',
28  '6',
29  '7',
30  '8',
31  '9',
32  'a',
33  'b',
34  'c',
35  'd',
36  'e',
37  'f'};
38  }
39 
48  template <size_t size_>
49  class blob_t : public std::array<byte_t, size_> {
50  public:
54  blob_t() {
55  this->fill(0);
56  }
57 
61  constexpr static size_t size() {
62  return size_;
63  }
64 
68  std::string to_string() const noexcept {
69  return std::string{this->begin(), this->end()};
70  }
71 
75  std::string to_hexstring() const noexcept {
76  std::string res(size_ * 2, 0);
77  auto ptr = this->data();
78  for (uint32_t i = 0, k = 0; i < size_; i++) {
79  const auto front = (uint8_t)(ptr[i] & 0xF0) >> 4;
80  const auto back = (uint8_t)(ptr[i] & 0xF);
81  res[k++] = code[front];
82  res[k++] = code[back];
83  }
84  return res;
85  }
86 
87  static blob_t<size_> from_string(const std::string &data) {
88  if (data.size() != size_) {
89  std::string value = "blob_t: input string has incorrect length. Found: "
90  + std::to_string(data.size())
91  + +", required: " + std::to_string(size_);
92  throw BadFormatException(value.c_str());
93  }
94 
95  blob_t<size_> b;
96  std::copy(data.begin(), data.end(), b.begin());
97 
98  return b;
99  }
100 
101  static blob_t<size_> from_hexstring(const std::string &hex) {
102  auto bytes = iroha::hexstringToBytestring(hex);
103  if (not bytes) {
104  throw BadFormatException(
105  "Provided data (" + hex
106  + ") is not a valid hex value for blob of size ("
107  + std::to_string(size_) + ").");
108  }
109  return from_string(*bytes);
110  }
111  };
112 } // namespace iroha
113 
114 #endif // IROHA_COMMON_BLOB_HPP
std::invalid_argument BadFormatException
Definition: blob.hpp:18
blob_t()
Definition: blob.hpp:54
std::string to_string(const Collection &collection, Lambda transform)
Definition: logger.hpp:132
static constexpr size_t size()
Definition: blob.hpp:61
std::string to_hexstring() const noexcept
Definition: blob.hpp:75
static blob_t< size_ > from_string(const std::string &data)
Definition: blob.hpp:87
std::string to_string() const noexcept
Definition: blob.hpp:68
Definition: block_query.hpp:14
boost::optional< std::string > hexstringToBytestring(const std::string &str)
Definition: hexutils.hpp:37
Definition: blob.hpp:49
static blob_t< size_ > from_hexstring(const std::string &hex)
Definition: blob.hpp:101
uint8_t byte_t
Definition: blob.hpp:19