ゴミ箱
varint.hpp
Go to the documentation of this file.
1 //
2 // Copyright (c) 2017 Vinnie Falco (vinnie dot falco at gmail dot com)
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // Official repository: https://github.com/boostorg/beast
8 //
9 
10 #ifndef BOOST_BEAST_DETAIL_VARINT_HPP
11 #define BOOST_BEAST_DETAIL_VARINT_HPP
12 
13 #include <boost/static_assert.hpp>
14 #include <cstdlib>
15 #include <iterator>
16 #include <type_traits>
17 
18 namespace boost {
19 namespace beast {
20 namespace detail {
21 
22 // https://developers.google.com/protocol-buffers/docs/encoding#varints
23 
24 inline
25 std::size_t
26 varint_size(std::size_t value)
27 {
28  std::size_t n = 1;
29  while(value > 127)
30  {
31  ++n;
32  value /= 128;
33  }
34  return n;
35 }
36 
37 template<class FwdIt>
38 std::size_t
39 varint_read(FwdIt& first)
40 {
41  using value_type = typename
42  std::iterator_traits<FwdIt>::value_type;
43  BOOST_STATIC_ASSERT(
44  std::is_integral<value_type>::value &&
45  sizeof(value_type) == 1);
46  std::size_t value = 0;
47  std::size_t factor = 1;
48  while((*first & 0x80) != 0)
49  {
50  value += (*first++ & 0x7f) * factor;
51  factor *= 128;
52  }
53  value += *first++ * factor;
54  return value;
55 }
56 
57 template<class FwdIt>
58 void
59 varint_write(FwdIt& first, std::size_t value)
60 {
61  using value_type = typename
62  std::iterator_traits<FwdIt>::value_type;
63  BOOST_STATIC_ASSERT(
64  std::is_integral<value_type>::value &&
65  sizeof(value_type) == 1);
66  while(value > 127)
67  {
68  *first++ = static_cast<value_type>(
69  0x80 | value);
70  value /= 128;
71  }
72  *first++ = static_cast<value_type>(value);
73 }
74 
75 } // detail
76 } // beast
77 } // boost
78 
79 #endif
Definition: async_result.hpp:20
std::size_t varint_read(FwdIt &first)
Definition: varint.hpp:39
std::size_t varint_size(std::size_t value)
Definition: varint.hpp:26
void varint_write(FwdIt &first, std::size_t value)
Definition: varint.hpp:59