hmath.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef HV_MATH_H_
  2. #define HV_MATH_H_
  3. #include <math.h>
  4. static inline unsigned long floor2e(unsigned long num) {
  5. unsigned long n = num;
  6. int e = 0;
  7. while (n>>=1) ++e;
  8. unsigned long ret = 1;
  9. while (e--) ret<<=1;
  10. return ret;
  11. }
  12. static inline unsigned long ceil2e(unsigned long num) {
  13. // 2**0 = 1
  14. if (num == 0 || num == 1) return 1;
  15. unsigned long n = num - 1;
  16. int e = 1;
  17. while (n>>=1) ++e;
  18. unsigned long ret = 1;
  19. while (e--) ret<<=1;
  20. return ret;
  21. }
  22. // varint little-endian
  23. // MSB
  24. static inline int varint_encode(long long value, unsigned char* buf) {
  25. unsigned char ch;
  26. unsigned char *p = buf;
  27. int bytes = 0;
  28. do {
  29. ch = value & 0x7F;
  30. value >>= 7;
  31. *p++ = value == 0 ? ch : (ch | 0x80);
  32. ++bytes;
  33. } while (value);
  34. return bytes;
  35. }
  36. // @param[IN|OUT] len: in=>buflen, out=>varint bytesize
  37. static inline long long varint_decode(const unsigned char* buf, int* len) {
  38. long long ret = 0;
  39. int bytes = 0, bits = 0;
  40. const unsigned char *p = buf;
  41. do {
  42. if (len && *len && bytes == *len) {
  43. // Not enough length
  44. *len = 0;
  45. return 0;
  46. }
  47. ret |= ((long long)(*p & 0x7F)) << bits;
  48. ++bytes;
  49. if ((*p & 0x80) == 0) {
  50. // Found end
  51. if (len) *len = bytes;
  52. return ret;
  53. }
  54. ++p;
  55. bits += 7;
  56. } while(bytes < 10);
  57. // Not found end
  58. if (len) *len = -1;
  59. return ret;
  60. }
  61. #endif // HV_MATH_H_