Zeth - Zerocash on Ethereum  0.8
Reference implementation of the Zeth protocol by Clearmatics
utils.tcc
Go to the documentation of this file.
1 // Copyright (c) 2015-2022 Clearmatics Technologies Ltd
2 //
3 // SPDX-License-Identifier: LGPL-3.0+
4 
5 #ifndef __ZETH_CORE_UTILS_TCC__
6 #define __ZETH_CORE_UTILS_TCC__
7 
8 #include "libzeth/core/utils.hpp"
9 
10 #include <cmath>
11 #include <stdexcept> // required for std::length_error on linux
12 
13 namespace libzeth
14 {
15 
16 template<> constexpr size_t bit_utils<0>::bit_size() { return 0; }
17 
18 template<> constexpr size_t bit_utils<0>::hamming_weight() { return 0; }
19 
20 template<size_t X> constexpr size_t bit_utils<X>::bit_size()
21 {
22  return 1 + bit_utils<(X >> 1)>::bit_size();
23 }
24 
25 template<size_t X> constexpr size_t bit_utils<X>::hamming_weight()
26 {
27  return (X & 1) + bit_utils<(X >> 1)>::hamming_weight();
28 }
29 
30 template<typename T> T swap_byte_endianness(T v)
31 {
32  size_t len = v.size();
33  if (len == 0) {
34  throw std::length_error(
35  "Invalid bit length for the given boolean vector (should be > 0)");
36  }
37  if (len % 8 != 0) {
38  throw std::length_error("Invalid bit length for the given boolean "
39  "vector (should be multiple of 8)");
40  }
41 
42  size_t byte_mid_length = std::ceil((len / 8) / 2);
43  for (size_t i = 0; i < byte_mid_length; i++) {
44  for (size_t j = 0; j < 8; j++) {
45  std::swap(v[8 * i + j], v[len - 8 * (i + 1) + j]);
46  }
47  }
48  return v;
49 }
50 
51 template<typename StructuredTs>
52 bool container_is_well_formed(const StructuredTs &values)
53 {
54  for (const auto &v : values) {
55  if (!v.is_well_formed()) {
56  return false;
57  }
58  }
59 
60  return true;
61 }
62 
63 template<typename StructuredT>
64 void check_well_formed(const StructuredT &v, const char *name)
65 {
66  if (!v.is_well_formed()) {
67  throw std::invalid_argument(std::string(name) + " not well-formed");
68  }
69 }
70 
71 } // namespace libzeth
72 
73 #endif // __ZETH_CORE_UTILS_TCC__