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