Base64.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- Base64.h - Base64 Encoder/Decoder ----------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file provides generic base64 encoder/decoder.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_BASE64_H
  18. #define LLVM_SUPPORT_BASE64_H
  19. #include <cstdint>
  20. #include <string>
  21. namespace llvm {
  22. template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) {
  23. static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  24. "abcdefghijklmnopqrstuvwxyz"
  25. "0123456789+/";
  26. std::string Buffer;
  27. Buffer.resize(((Bytes.size() + 2) / 3) * 4);
  28. size_t i = 0, j = 0;
  29. for (size_t n = Bytes.size() / 3 * 3; i < n; i += 3, j += 4) {
  30. uint32_t x = ((unsigned char)Bytes[i] << 16) |
  31. ((unsigned char)Bytes[i + 1] << 8) |
  32. (unsigned char)Bytes[i + 2];
  33. Buffer[j + 0] = Table[(x >> 18) & 63];
  34. Buffer[j + 1] = Table[(x >> 12) & 63];
  35. Buffer[j + 2] = Table[(x >> 6) & 63];
  36. Buffer[j + 3] = Table[x & 63];
  37. }
  38. if (i + 1 == Bytes.size()) {
  39. uint32_t x = ((unsigned char)Bytes[i] << 16);
  40. Buffer[j + 0] = Table[(x >> 18) & 63];
  41. Buffer[j + 1] = Table[(x >> 12) & 63];
  42. Buffer[j + 2] = '=';
  43. Buffer[j + 3] = '=';
  44. } else if (i + 2 == Bytes.size()) {
  45. uint32_t x =
  46. ((unsigned char)Bytes[i] << 16) | ((unsigned char)Bytes[i + 1] << 8);
  47. Buffer[j + 0] = Table[(x >> 18) & 63];
  48. Buffer[j + 1] = Table[(x >> 12) & 63];
  49. Buffer[j + 2] = Table[(x >> 6) & 63];
  50. Buffer[j + 3] = '=';
  51. }
  52. return Buffer;
  53. }
  54. } // end namespace llvm
  55. #endif
  56. #ifdef __GNUC__
  57. #pragma GCC diagnostic pop
  58. #endif