base64.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Copyright (c) 2020 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #if RTC_ENABLE_WEBSOCKET
  19. #include "base64.hpp"
  20. namespace rtc {
  21. using std::to_integer;
  22. string to_base64(const binary &data) {
  23. static const char tab[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  24. string out;
  25. out.reserve(3 * ((data.size() + 3) / 4));
  26. int i = 0;
  27. while (data.size() - i >= 3) {
  28. auto d0 = to_integer<uint8_t>(data[i]);
  29. auto d1 = to_integer<uint8_t>(data[i + 1]);
  30. auto d2 = to_integer<uint8_t>(data[i + 2]);
  31. out += tab[d0 >> 2];
  32. out += tab[((d0 & 3) << 4) | (d1 >> 4)];
  33. out += tab[((d1 & 0x0F) << 2) | (d2 >> 6)];
  34. out += tab[d2 & 0x3F];
  35. i += 3;
  36. }
  37. int left = int(data.size() - i);
  38. if (left) {
  39. auto d0 = to_integer<uint8_t>(data[i]);
  40. out += tab[d0 >> 2];
  41. if (left == 1) {
  42. out += tab[(d0 & 3) << 4];
  43. out += '=';
  44. } else { // left == 2
  45. auto d1 = to_integer<uint8_t>(data[i + 1]);
  46. out += tab[((d0 & 3) << 4) | (d1 >> 4)];
  47. out += tab[(d1 & 0x0F) << 2];
  48. }
  49. out += '=';
  50. }
  51. return out;
  52. }
  53. } // namespace rtc
  54. #endif