tools.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. #include <stdint.h>
  2. #include <algorithm>
  3. #include <array>
  4. #include <string.h>
  5. #include <tools.h>
  6. uint32_t hash(const void*d,int len)
  7. {
  8. uint8_t*db=(uint8_t*)d;
  9. uint32_t h=0;
  10. for(int i=0;i<len;i++)
  11. {
  12. h*=50793233;
  13. h^=db[i];
  14. }
  15. h ^= (h>>13) ^ (h>>23);
  16. return h ^ (h >> 9) ^ (h >> 5);
  17. }
  18. struct bin_format
  19. {
  20. char *_buff;
  21. char *code1[256], *code2[256];
  22. bin_format()
  23. {
  24. _buff=(char*)malloc(1024+512);
  25. int n;
  26. char*p=_buff;
  27. for(int i=0;i<256;i++)
  28. {
  29. n=sprintf(p,"%02X ",i);
  30. code1[i]=p;
  31. p+=n+1;
  32. n=sprintf(p,"%c",std::isprint(i)?i:'.');
  33. code2[i]=p;
  34. p+=n+1;
  35. }
  36. }
  37. ~bin_format()
  38. {
  39. free(_buff);
  40. }
  41. void format_line2(std::string&rt,const char*b,const char*e)
  42. {
  43. char b1[256];
  44. char*p1=b1;
  45. for(;b!=e;b++)
  46. {
  47. uint8_t ch=*b;
  48. strcpy(p1,code1[ch]); p1+=3;
  49. }
  50. *p1=0;
  51. rt.append(b1,p1);
  52. rt.append("\n");
  53. }
  54. std::string do_format2(const char*d,size_t len)
  55. {
  56. std::string rt;
  57. rt.reserve(len*4);
  58. int line=len>>5;
  59. for(int i=0;i<line;i++)
  60. {
  61. const char*t=d+(i<<5);
  62. format_line2(rt,t,t+32);
  63. }
  64. if(len%32)
  65. {
  66. format_line2(rt,d+(len>>5<<5),d+len);
  67. }
  68. return std::move(rt);
  69. }
  70. void format_line(std::string&rt,const char*b,const char*e)
  71. {
  72. char b1[256], b2[128];
  73. char*p1=b1,*p2=b2;
  74. for(;b!=e;b++)
  75. {
  76. uint8_t ch=*b;
  77. strcpy(p1,code1[ch]); p1+=3;
  78. strcpy(p2,code2[ch]); p2+=1;
  79. }
  80. *p1=0;*p2=0;
  81. rt.append(b1,p1);
  82. rt.append(48-(p1-b1)+8,' ');
  83. rt.append(b2,p2);
  84. rt.append("\n");
  85. }
  86. std::string do_format(const char*d,size_t len)
  87. {
  88. std::string rt;
  89. rt.reserve(len*4+len);
  90. int line=len>>4;
  91. for(int i=0;i<line;i++)
  92. {
  93. const char*t=d+(i<<4);
  94. format_line(rt,t,t+16);
  95. }
  96. if(len%16)
  97. {
  98. format_line(rt,d+(len>>4<<4),d+len);
  99. }
  100. return std::move(rt);
  101. }
  102. };
  103. std::string format_bin(const char*d,int len)
  104. {
  105. static bin_format format;
  106. return std::move(format.do_format(d,len));
  107. }
  108. std::string format_bin2(const char*d,int len)
  109. {
  110. static bin_format format;
  111. return std::move(format.do_format2(d,len));
  112. }