pstore2
base32.hpp
Go to the documentation of this file.
1 //===- lib/core/base32.hpp --------------------------------*- mode: C++ -*-===//
2 //* _ _________ *
3 //* | |__ __ _ ___ ___|___ /___ \ *
4 //* | '_ \ / _` / __|/ _ \ |_ \ __) | *
5 //* | |_) | (_| \__ \ __/___) / __/ *
6 //* |_.__/ \__,_|___/\___|____/_____| *
7 //* *
8 //===----------------------------------------------------------------------===//
9 //
10 // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
11 // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
12 // information.
13 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
14 //
15 //===----------------------------------------------------------------------===//
17 
18 #ifndef PSTORE_CORE_BASE32_HPP
19 #define PSTORE_CORE_BASE32_HPP
20 
21 #include <algorithm>
22 #include <cmath>
23 
25 
26 namespace pstore {
27  namespace base32 {
28 
29 
30  extern std::array<char const, 32> const alphabet;
31 
35  template <typename IntType, typename OutputIterator>
36  OutputIterator convert (IntType val, OutputIterator out) {
37  PSTORE_STATIC_ASSERT (std::is_unsigned<IntType>::value);
38  constexpr auto mask = (1U << 5) - 1U;
39  PSTORE_ASSERT (mask == alphabet.size () - 1U);
40  do {
41  *(out++) = alphabet[val & mask];
42  } while (val >>= 5);
43  return out;
44  }
45 
46  template <typename OutputIterator>
47  OutputIterator convert (uint128 const wide, OutputIterator out) {
48  auto high = wide.high ();
49  auto low = wide.low ();
50  constexpr auto mask = (1U << 5) - 1U;
51  PSTORE_ASSERT (mask == alphabet.size () - 1U);
52  do {
53  *(out++) = alphabet[low & mask];
54  low >>= 5;
55  low |= (high & mask) << (64 - 5);
56  high >>= 5;
57  } while ((low | high) != 0);
58  return out;
59  }
60 
64  template <typename IntType>
65  std::string convert (IntType val) {
66  std::string result;
67  auto const max_length = 26;
68  PSTORE_ASSERT (std::pow (32.0, max_length) >= std::pow (2.0, 128));
69  result.reserve (max_length);
70  convert (val, std::back_inserter (result));
71  return result;
72  }
73 
74  } // namespace base32
75 } // namespace pstore
76 
77 #endif // PSTORE_CORE_BASE32_HPP
Definition: uint128.hpp:85
Declares a portable 128-bit integer type.
OutputIterator convert(IntType val, OutputIterator out)
Converts an unsigned integer value to a sequence of base-32 characters.
Definition: base32.hpp:36
Definition: nonpod2.cpp:40