You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HexInStream.cxx 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. *
  3. * This is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This software is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this software; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  16. * USA.
  17. */
  18. #include <rdr/HexInStream.h>
  19. #include <rdr/Exception.h>
  20. #include <stdlib.h>
  21. #include <ctype.h>
  22. using namespace rdr;
  23. static inline int min(int a, int b) {return a<b ? a : b;}
  24. HexInStream::HexInStream(InStream& is)
  25. : in_stream(is)
  26. {
  27. }
  28. HexInStream::~HexInStream() {
  29. }
  30. bool HexInStream::readHexAndShift(char c, int* v) {
  31. c=tolower(c);
  32. if ((c >= '0') && (c <= '9'))
  33. *v = (*v << 4) + (c - '0');
  34. else if ((c >= 'a') && (c <= 'f'))
  35. *v = (*v << 4) + (c - 'a' + 10);
  36. else
  37. return false;
  38. return true;
  39. }
  40. bool HexInStream::hexStrToBin(const char* s, char** data, size_t* length) {
  41. size_t l=strlen(s);
  42. if ((l % 2) == 0) {
  43. delete [] *data;
  44. *data = 0; *length = 0;
  45. if (l == 0)
  46. return true;
  47. *data = new char[l/2];
  48. *length = l/2;
  49. for(size_t i=0;i<l;i+=2) {
  50. int byte = 0;
  51. if (!readHexAndShift(s[i], &byte) ||
  52. !readHexAndShift(s[i+1], &byte))
  53. goto decodeError;
  54. (*data)[i/2] = byte;
  55. }
  56. return true;
  57. }
  58. decodeError:
  59. delete [] *data;
  60. *data = 0;
  61. *length = 0;
  62. return false;
  63. }
  64. bool HexInStream::fillBuffer(size_t maxSize, bool wait) {
  65. if (!in_stream.hasData(2))
  66. return false;
  67. size_t length = min(in_stream.avail()/2, maxSize);
  68. const U8* iptr = in_stream.getptr(length*2);
  69. U8* optr = (U8*) end;
  70. for (size_t i=0; i<length; i++) {
  71. int v = 0;
  72. readHexAndShift(iptr[i*2], &v);
  73. readHexAndShift(iptr[i*2+1], &v);
  74. optr[i] = v;
  75. }
  76. in_stream.setptr(length*2);
  77. end += length;
  78. return true;
  79. }