base64.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #ifndef HV_BASE64_H_
  2. #define HV_BASE64_H_
  3. #include "hexport.h"
  4. #define BASE64_ENCODE_OUT_SIZE(s) (((s) + 2) / 3 * 4)
  5. #define BASE64_DECODE_OUT_SIZE(s) (((s) + 3) / 4 * 3)
  6. BEGIN_EXTERN_C
  7. // @return encoded size
  8. HV_EXPORT int hv_base64_encode(const unsigned char *in, unsigned int inlen, char *out);
  9. // @return decoded size
  10. HV_EXPORT int hv_base64_decode(const char *in, unsigned int inlen, unsigned char *out);
  11. END_EXTERN_C
  12. #ifdef __cplusplus
  13. #include <string.h>
  14. #include <string>
  15. namespace hv {
  16. HV_INLINE std::string Base64Encode(const unsigned char* data, unsigned int len) {
  17. int encoded_size = BASE64_ENCODE_OUT_SIZE(len);
  18. std::string encoded_str(encoded_size + 1, 0);
  19. encoded_size = hv_base64_encode(data, len, (char*)encoded_str.data());
  20. encoded_str.resize(encoded_size);
  21. return encoded_str;
  22. }
  23. HV_INLINE std::string Base64Decode(const char* str, unsigned int len = 0) {
  24. if (len == 0) len = strlen(str);
  25. int decoded_size = BASE64_DECODE_OUT_SIZE(len);
  26. std::string decoded_buf(decoded_size + 1, 0);
  27. decoded_size = hv_base64_decode(str, len, (unsigned char*)decoded_buf.data());
  28. if (decoded_size > 0) {
  29. decoded_buf.resize(decoded_size);
  30. } else {
  31. decoded_buf.clear();
  32. }
  33. return decoded_buf;
  34. }
  35. }
  36. #endif
  37. #endif // HV_BASE64_H_