Counter Strike : Global Offensive Source Code
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.

82 lines
2.0 KiB

  1. //===== Copyright c 1996-2008, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose: Simple encoder/decoder
  4. //
  5. //===========================================================================//
  6. #ifndef COMMON_SIMPLE_CODEC
  7. #define COMMON_SIMPLE_CODEC
  8. #include <stdlib.h>
  9. namespace SimpleCodec
  10. {
  11. //
  12. // Encodes the buffer in place
  13. // pvBuffer pointer to the base of the buffer, buffer length is "numBytes + numSultBytes"
  14. // numBytes number of real data bytes already in the buffer
  15. // numSultBytes number of sult bytes to be placed after the buffer data
  16. //
  17. inline void EncodeBuffer( unsigned char *pvBuffer, int numBytes, unsigned char numSultBytes )
  18. {
  19. unsigned char xx = 0xA7;
  20. // Add some sult in the very end
  21. Assert( numSultBytes > 0 );
  22. pvBuffer[ numBytes + numSultBytes - 1 ] = numSultBytes;
  23. -- numSultBytes;
  24. // Store sult data
  25. for ( unsigned char *pvSult = pvBuffer + numBytes;
  26. numSultBytes -- > 0; ++ pvSult )
  27. {
  28. *pvSult = rand() % 0x100;
  29. xx ^= ( *pvSult + 0xA7 ) % 0x100;
  30. }
  31. // Hash the buffer
  32. for ( ; numBytes -- > 0; ++ pvBuffer )
  33. {
  34. unsigned char v = *pvBuffer;
  35. v ^= xx;
  36. xx = ( v + 0xA7 ) % 0x100;
  37. *pvBuffer = v;
  38. }
  39. }
  40. //
  41. // Decodes the buffer in place
  42. // pvBuffer pointer to the base of the encoded buffer
  43. // numBytes number of buffer bytes on input
  44. // on return contains the number of data bytes decoded (excludes sult)
  45. //
  46. inline void DecodeBuffer( unsigned char *pvBuffer, int &numBytes )
  47. {
  48. unsigned char xx = 0xA7;
  49. // Discover the number of sult bytes
  50. unsigned char numSultBytes = pvBuffer[ numBytes - 1 ];
  51. numBytes -= numSultBytes;
  52. -- numSultBytes;
  53. // Recover sult data
  54. for ( unsigned char *pvSult = pvBuffer + numBytes;
  55. numSultBytes -- > 0; ++ pvSult )
  56. {
  57. xx ^= ( *pvSult + 0xA7 ) % 0x100;
  58. }
  59. // Hash the buffer
  60. for ( int numBufBytes = numBytes; numBufBytes -- > 0; ++ pvBuffer )
  61. {
  62. unsigned char v = *pvBuffer;
  63. v ^= xx;
  64. xx = ( *pvBuffer + 0xA7 ) % 0x100;
  65. *pvBuffer = v;
  66. }
  67. }
  68. }; // namespace SimpleCodec
  69. #endif // COMMON_SIMPLE_CODEC