]> git.proxmox.com Git - ceph.git/blob - ceph/src/rgw/rgw_b64.h
update sources to v12.1.0
[ceph.git] / ceph / src / rgw / rgw_b64.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #ifndef RGW_B64_H
5 #define RGW_B64_H
6
7 #include <boost/utility/string_ref.hpp>
8 #include <boost/utility/string_view.hpp>
9 #include <boost/archive/iterators/base64_from_binary.hpp>
10 #include <boost/archive/iterators/binary_from_base64.hpp>
11 #include <boost/archive/iterators/insert_linebreaks.hpp>
12 #include <boost/archive/iterators/transform_width.hpp>
13 #include <boost/archive/iterators/remove_whitespace.hpp>
14 #include <limits>
15
16 namespace rgw {
17
18 /*
19 * A header-only Base64 encoder built on boost::archive. The
20 * formula is based on a class poposed for inclusion in boost in
21 * 2011 by Denis Shevchenko (abandoned), updated slightly
22 * (e.g., uses boost::string_view).
23 *
24 * Also, wrap_width added as template argument, based on
25 * feedback from Marcus.
26 */
27
28 template<int wrap_width = std::numeric_limits<int>::max()>
29 inline std::string to_base64(boost::string_view sview)
30 {
31 using namespace boost::archive::iterators;
32
33 // output must be =padded modulo 3
34 auto psize = sview.size();
35 while ((psize % 3) != 0) {
36 ++psize;
37 }
38
39 /* RFC 2045 requires linebreaks to be present in the output
40 * sequence every at-most 76 characters (MIME-compliance),
41 * but we could likely omit it. */
42 typedef
43 insert_linebreaks<
44 base64_from_binary<
45 transform_width<
46 boost::string_view::const_iterator
47 ,6,8>
48 >
49 ,wrap_width
50 > b64_iter;
51
52 std::string outstr(b64_iter(sview.data()),
53 b64_iter(sview.data() + sview.size()));
54
55 // pad outstr with '=' to a length that is a multiple of 3
56 for (size_t ix = 0; ix < (psize-sview.size()); ++ix)
57 outstr.push_back('=');
58
59 return outstr;
60 }
61
62 inline std::string from_base64(boost::string_view sview)
63 {
64 using namespace boost::archive::iterators;
65 if (sview.empty())
66 return std::string();
67 /* MIME-compliant input will have line-breaks, so we have to
68 * filter WS */
69 typedef
70 transform_width<
71 binary_from_base64<
72 remove_whitespace<
73 boost::string_view::const_iterator>>
74 ,8,6
75 > b64_iter;
76
77 while (sview.back() == '=')
78 sview.remove_suffix(1);
79
80 std::string outstr(b64_iter(sview.data()),
81 b64_iter(sview.data() + sview.size()));
82
83 return outstr;
84 }
85 } /* namespace */
86
87 #endif /* RGW_B64_H */