Move initial TLS write record layer code into new structure
[openssl.git] / crypto / quic_vlint.c
1 #include "internal/quic_vlint.h"
2 #include "internal/e_os.h"
3
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
28 void ossl_quic_vlint_encode(uint8_t *buf, uint64_t v)
29 {
30     ossl_quic_vlint_encode_n(buf, v, ossl_quic_vlint_encode_len(v));
31 }
32
33 uint64_t ossl_quic_vlint_decode_unchecked(const unsigned char *buf)
34 {
35     uint8_t first_byte = buf[0];
36     size_t sz = ossl_quic_vlint_decode_len(first_byte);
37
38     if (sz == 1)
39         return first_byte & 0x3F;
40
41     if (sz == 2)
42         return ((uint64_t)(first_byte & 0x3F) << 8)
43              | buf[1];
44
45     if (sz == 4)
46         return ((uint64_t)(first_byte & 0x3F) << 24)
47              | ((uint64_t)buf[1] << 16)
48              | ((uint64_t)buf[2] <<  8)
49              |  buf[3];
50
51     return ((uint64_t)(first_byte & 0x3F) << 56)
52          | ((uint64_t)buf[1] << 48)
53          | ((uint64_t)buf[2] << 40)
54          | ((uint64_t)buf[3] << 32)
55          | ((uint64_t)buf[4] << 24)
56          | ((uint64_t)buf[5] << 16)
57          | ((uint64_t)buf[6] <<  8)
58          |  buf[7];
59 }
60
61 int ossl_quic_vlint_decode(const unsigned char *buf, size_t buf_len, uint64_t *v)
62 {
63     size_t dec_len;
64     uint64_t x;
65
66     if (buf_len < 1)
67         return 0;
68
69     dec_len = ossl_quic_vlint_decode_len(buf[0]);
70     if (buf_len < dec_len)
71         return 0;
72
73     x = ossl_quic_vlint_decode_unchecked(buf);
74
75     *v = x;
76     return dec_len;
77 }