quic_vlint.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "internal/quic_vlint.h"
  2. #include "internal/e_os.h"
  3. #ifndef OPENSSL_NO_QUIC
  4. void ossl_quic_vlint_encode_n(uint8_t *buf, uint64_t v, int n)
  5. {
  6. if (n == 1) {
  7. buf[0] = (uint8_t)v;
  8. } else if (n == 2) {
  9. buf[0] = (uint8_t)(0x40 | ((v >> 8) & 0x3F));
  10. buf[1] = (uint8_t)v;
  11. } else if (n == 4) {
  12. buf[0] = (uint8_t)(0x80 | ((v >> 24) & 0x3F));
  13. buf[1] = (uint8_t)(v >> 16);
  14. buf[2] = (uint8_t)(v >> 8);
  15. buf[3] = (uint8_t)v;
  16. } else {
  17. buf[0] = (uint8_t)(0xC0 | ((v >> 56) & 0x3F));
  18. buf[1] = (uint8_t)(v >> 48);
  19. buf[2] = (uint8_t)(v >> 40);
  20. buf[3] = (uint8_t)(v >> 32);
  21. buf[4] = (uint8_t)(v >> 24);
  22. buf[5] = (uint8_t)(v >> 16);
  23. buf[6] = (uint8_t)(v >> 8);
  24. buf[7] = (uint8_t)v;
  25. }
  26. }
  27. void ossl_quic_vlint_encode(uint8_t *buf, uint64_t v)
  28. {
  29. ossl_quic_vlint_encode_n(buf, v, ossl_quic_vlint_encode_len(v));
  30. }
  31. uint64_t ossl_quic_vlint_decode_unchecked(const unsigned char *buf)
  32. {
  33. uint8_t first_byte = buf[0];
  34. size_t sz = ossl_quic_vlint_decode_len(first_byte);
  35. if (sz == 1)
  36. return first_byte & 0x3F;
  37. if (sz == 2)
  38. return ((uint64_t)(first_byte & 0x3F) << 8)
  39. | buf[1];
  40. if (sz == 4)
  41. return ((uint64_t)(first_byte & 0x3F) << 24)
  42. | ((uint64_t)buf[1] << 16)
  43. | ((uint64_t)buf[2] << 8)
  44. | buf[3];
  45. return ((uint64_t)(first_byte & 0x3F) << 56)
  46. | ((uint64_t)buf[1] << 48)
  47. | ((uint64_t)buf[2] << 40)
  48. | ((uint64_t)buf[3] << 32)
  49. | ((uint64_t)buf[4] << 24)
  50. | ((uint64_t)buf[5] << 16)
  51. | ((uint64_t)buf[6] << 8)
  52. | buf[7];
  53. }
  54. int ossl_quic_vlint_decode(const unsigned char *buf, size_t buf_len, uint64_t *v)
  55. {
  56. size_t dec_len;
  57. uint64_t x;
  58. if (buf_len < 1)
  59. return 0;
  60. dec_len = ossl_quic_vlint_decode_len(buf[0]);
  61. if (buf_len < dec_len)
  62. return 0;
  63. x = ossl_quic_vlint_decode_unchecked(buf);
  64. *v = x;
  65. return dec_len;
  66. }
  67. #endif