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.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #ifdef HAVE_CONFIG_H
  19. #include <config.h>
  20. #endif
  21. #include <rdr/HexInStream.h>
  22. #include <rdr/Exception.h>
  23. #include <stdlib.h>
  24. #include <ctype.h>
  25. using namespace rdr;
  26. static inline int min(int a, int b) {return a<b ? a : b;}
  27. HexInStream::HexInStream(InStream& is)
  28. : in_stream(is)
  29. {
  30. }
  31. HexInStream::~HexInStream() {
  32. }
  33. bool HexInStream::readHexAndShift(char c, int* v) {
  34. c=tolower(c);
  35. if ((c >= '0') && (c <= '9'))
  36. *v = (*v << 4) + (c - '0');
  37. else if ((c >= 'a') && (c <= 'f'))
  38. *v = (*v << 4) + (c - 'a' + 10);
  39. else
  40. return false;
  41. return true;
  42. }
  43. bool HexInStream::hexStrToBin(const char* s, char** data, size_t* length) {
  44. size_t l=strlen(s);
  45. if ((l % 2) == 0) {
  46. delete [] *data;
  47. *data = 0; *length = 0;
  48. if (l == 0)
  49. return true;
  50. *data = new char[l/2];
  51. *length = l/2;
  52. for(size_t i=0;i<l;i+=2) {
  53. int byte = 0;
  54. if (!readHexAndShift(s[i], &byte) ||
  55. !readHexAndShift(s[i+1], &byte))
  56. goto decodeError;
  57. (*data)[i/2] = byte;
  58. }
  59. return true;
  60. }
  61. decodeError:
  62. delete [] *data;
  63. *data = 0;
  64. *length = 0;
  65. return false;
  66. }
  67. bool HexInStream::fillBuffer(size_t maxSize) {
  68. if (!in_stream.hasData(2))
  69. return false;
  70. size_t length = min(in_stream.avail()/2, maxSize);
  71. const U8* iptr = in_stream.getptr(length*2);
  72. U8* optr = (U8*) end;
  73. for (size_t i=0; i<length; i++) {
  74. int v = 0;
  75. readHexAndShift(iptr[i*2], &v);
  76. readHexAndShift(iptr[i*2+1], &v);
  77. optr[i] = v;
  78. }
  79. in_stream.setptr(length*2);
  80. end += length;
  81. return true;
  82. }