Base64.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 "llvm/Support/Error.h"
  20. #include <cstdint>
  21. #include <string>
  22. #include <vector>
  23. namespace llvm {
  24. template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) {
  25. static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  26. "abcdefghijklmnopqrstuvwxyz"
  27. "0123456789+/";
  28. std::string Buffer;
  29. Buffer.resize(((Bytes.size() + 2) / 3) * 4);
  30. size_t i = 0, j = 0;
  31. for (size_t n = Bytes.size() / 3 * 3; i < n; i += 3, j += 4) {
  32. uint32_t x = ((unsigned char)Bytes[i] << 16) |
  33. ((unsigned char)Bytes[i + 1] << 8) |
  34. (unsigned char)Bytes[i + 2];
  35. Buffer[j + 0] = Table[(x >> 18) & 63];
  36. Buffer[j + 1] = Table[(x >> 12) & 63];
  37. Buffer[j + 2] = Table[(x >> 6) & 63];
  38. Buffer[j + 3] = Table[x & 63];
  39. }
  40. if (i + 1 == Bytes.size()) {
  41. uint32_t x = ((unsigned char)Bytes[i] << 16);
  42. Buffer[j + 0] = Table[(x >> 18) & 63];
  43. Buffer[j + 1] = Table[(x >> 12) & 63];
  44. Buffer[j + 2] = '=';
  45. Buffer[j + 3] = '=';
  46. } else if (i + 2 == Bytes.size()) {
  47. uint32_t x =
  48. ((unsigned char)Bytes[i] << 16) | ((unsigned char)Bytes[i + 1] << 8);
  49. Buffer[j + 0] = Table[(x >> 18) & 63];
  50. Buffer[j + 1] = Table[(x >> 12) & 63];
  51. Buffer[j + 2] = Table[(x >> 6) & 63];
  52. Buffer[j + 3] = '=';
  53. }
  54. return Buffer;
  55. }
  56. llvm::Error decodeBase64(llvm::StringRef Input, std::vector<char> &Output);
  57. } // end namespace llvm
  58. #endif
  59. #ifdef __GNUC__
  60. #pragma GCC diagnostic pop
  61. #endif