1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
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>
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).
24 * Also, wrap_width added as template argument, based on
25 * feedback from Marcus.
28 template<int wrap_width = std::numeric_limits<int>::max()>
29 inline std::string to_base64(boost::string_view sview)
31 using namespace boost::archive::iterators;
33 // output must be =padded modulo 3
34 auto psize = sview.size();
35 while ((psize % 3) != 0) {
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. */
46 boost::string_view::const_iterator
52 std::string outstr(b64_iter(sview.data()),
53 b64_iter(sview.data() + sview.size()));
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('=');
62 inline std::string from_base64(boost::string_view sview)
64 using namespace boost::archive::iterators;
67 /* MIME-compliant input will have line-breaks, so we have to
73 boost::string_view::const_iterator>>
77 while (sview.back() == '=')
78 sview.remove_suffix(1);
80 std::string outstr(b64_iter(sview.data()),
81 b64_iter(sview.data() + sview.size()));
87 #endif /* RGW_B64_H */