b64.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Copyright (c) 2006-2011 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "b64.h"
  21. namespace love
  22. {
  23. static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
  24. void b64_decode_block(char in[4], char out[3])
  25. {
  26. out[0] = (char)(in[0] << 2 | in[1] >> 4);
  27. out[1] = (char)(in[1] << 4 | in[2] >> 2);
  28. out[2] = (char)(((in[2] << 6) & 0xc0) | in[3]);
  29. }
  30. char * b64_decode(const char * src, int slen, int & size)
  31. {
  32. size = (slen / 4) * 3;
  33. char * dst = new char[size];
  34. char * d = dst;
  35. char in[4], out[3], v;
  36. int i, len, pos = 0;
  37. while(pos <= slen)
  38. {
  39. for(len = 0, i = 0; i < 4 && pos <= slen; i++ )
  40. {
  41. v = 0;
  42. while(pos <= slen && v == 0 )
  43. {
  44. v = src[pos++];
  45. v = (char)((v < 43 || v > 122) ? 0 : cd64[v - 43]);
  46. if(v)
  47. v = (char)((v == '$') ? 0 : v - 61);
  48. }
  49. if(pos <= slen)
  50. {
  51. len++;
  52. if(v)
  53. in[i] = (char)(v - 1);
  54. }
  55. else
  56. in[i] = 0;
  57. }
  58. if(len) {
  59. b64_decode_block(in, out);
  60. for(i = 0; i < len - 1; i++)
  61. *(d++) = out[i];
  62. }
  63. }
  64. return dst;
  65. }
  66. } // love