rwebtransport 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/Cargo.lock +666 -0
  2. package/Cargo.toml +31 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +41 -0
  5. package/README.md +550 -0
  6. package/crates/echo-server/Cargo.toml +20 -0
  7. package/crates/echo-server/src/main.rs +666 -0
  8. package/crates/native/Cargo.toml +23 -0
  9. package/crates/native/src/config.rs +129 -0
  10. package/crates/native/src/driver.rs +463 -0
  11. package/crates/native/src/lib.rs +821 -0
  12. package/crates/native/src/server.rs +718 -0
  13. package/crates/native/src/session.rs +1191 -0
  14. package/crates/native/src/tls.rs +96 -0
  15. package/crates/wtcore/Cargo.toml +15 -0
  16. package/crates/wtcore/src/h3.rs +226 -0
  17. package/crates/wtcore/src/lib.rs +9 -0
  18. package/dist/datagrams.d.ts +16 -0
  19. package/dist/errors.d.ts +10 -0
  20. package/dist/index.d.ts +7 -0
  21. package/dist/index.js +1512 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/index.mjs +1473 -0
  24. package/dist/index.mjs.map +1 -0
  25. package/dist/loader.d.ts +2 -0
  26. package/dist/native.d.ts +226 -0
  27. package/dist/server.d.ts +44 -0
  28. package/dist/streams.d.ts +14 -0
  29. package/dist/types.d.ts +24 -0
  30. package/dist/webtransport.d.ts +20 -0
  31. package/package.json +79 -0
  32. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  33. package/scripts/bench.mjs +180 -0
  34. package/scripts/build.js +67 -0
  35. package/scripts/postinstall.js +67 -0
  36. package/scripts/setup-unix.sh +129 -0
  37. package/scripts/setup-windows.ps1 +229 -0
  38. package/vendor/quiche/AGENTS.md +75 -0
  39. package/vendor/quiche/COPYING +23 -0
  40. package/vendor/quiche/Cargo.lock +1212 -0
  41. package/vendor/quiche/Cargo.toml +215 -0
  42. package/vendor/quiche/README.md +466 -0
  43. package/vendor/quiche/examples/Makefile +46 -0
  44. package/vendor/quiche/examples/README.md +20 -0
  45. package/vendor/quiche/examples/cert-big.crt +90 -0
  46. package/vendor/quiche/examples/cert.crt +18 -0
  47. package/vendor/quiche/examples/cert.key +28 -0
  48. package/vendor/quiche/examples/client.c +343 -0
  49. package/vendor/quiche/examples/client.rs +281 -0
  50. package/vendor/quiche/examples/gen-certs.sh +15 -0
  51. package/vendor/quiche/examples/http3-client.c +473 -0
  52. package/vendor/quiche/examples/http3-client.rs +349 -0
  53. package/vendor/quiche/examples/http3-server.c +614 -0
  54. package/vendor/quiche/examples/http3-server.rs +680 -0
  55. package/vendor/quiche/examples/qpack-decode.rs +87 -0
  56. package/vendor/quiche/examples/qpack-encode.rs +88 -0
  57. package/vendor/quiche/examples/rootca.crt +21 -0
  58. package/vendor/quiche/examples/server.c +529 -0
  59. package/vendor/quiche/examples/server.rs +529 -0
  60. package/vendor/quiche/include/quiche.h +1282 -0
  61. package/vendor/quiche/quiche.svg +1 -0
  62. package/vendor/quiche/src/buffers.rs +105 -0
  63. package/vendor/quiche/src/build.rs +66 -0
  64. package/vendor/quiche/src/cid.rs +1079 -0
  65. package/vendor/quiche/src/crypto/boringssl.rs +373 -0
  66. package/vendor/quiche/src/crypto/mod.rs +671 -0
  67. package/vendor/quiche/src/dgram.rs +118 -0
  68. package/vendor/quiche/src/error.rs +263 -0
  69. package/vendor/quiche/src/ffi.rs +2290 -0
  70. package/vendor/quiche/src/flowcontrol.rs +246 -0
  71. package/vendor/quiche/src/frame.rs +2172 -0
  72. package/vendor/quiche/src/h3/AGENTS.md +54 -0
  73. package/vendor/quiche/src/h3/ffi.rs +442 -0
  74. package/vendor/quiche/src/h3/frame.rs +1404 -0
  75. package/vendor/quiche/src/h3/mod.rs +8223 -0
  76. package/vendor/quiche/src/h3/qpack/decoder.rs +288 -0
  77. package/vendor/quiche/src/h3/qpack/encoder.rs +235 -0
  78. package/vendor/quiche/src/h3/qpack/mod.rs +202 -0
  79. package/vendor/quiche/src/h3/qpack/static_table.rs +323 -0
  80. package/vendor/quiche/src/h3/stream.rs +1595 -0
  81. package/vendor/quiche/src/lib.rs +9556 -0
  82. package/vendor/quiche/src/minmax.rs +446 -0
  83. package/vendor/quiche/src/packet.rs +2334 -0
  84. package/vendor/quiche/src/path.rs +1374 -0
  85. package/vendor/quiche/src/pmtud.rs +652 -0
  86. package/vendor/quiche/src/rand.rs +64 -0
  87. package/vendor/quiche/src/range_buf.rs +186 -0
  88. package/vendor/quiche/src/ranges.rs +755 -0
  89. package/vendor/quiche/src/recovery/AGENTS.md +80 -0
  90. package/vendor/quiche/src/recovery/bandwidth.rs +565 -0
  91. package/vendor/quiche/src/recovery/bytes_in_flight.rs +179 -0
  92. package/vendor/quiche/src/recovery/congestion/cubic.rs +1038 -0
  93. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +514 -0
  94. package/vendor/quiche/src/recovery/congestion/hystart.rs +241 -0
  95. package/vendor/quiche/src/recovery/congestion/mod.rs +361 -0
  96. package/vendor/quiche/src/recovery/congestion/prr.rs +238 -0
  97. package/vendor/quiche/src/recovery/congestion/recovery.rs +1170 -0
  98. package/vendor/quiche/src/recovery/congestion/reno.rs +291 -0
  99. package/vendor/quiche/src/recovery/congestion/test_sender.rs +201 -0
  100. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +1947 -0
  101. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +158 -0
  102. package/vendor/quiche/src/recovery/gcongestion/bbr.rs +37 -0
  103. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +120 -0
  104. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +318 -0
  105. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +784 -0
  106. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +729 -0
  107. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +175 -0
  108. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +190 -0
  109. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +855 -0
  110. package/vendor/quiche/src/recovery/gcongestion/mod.rs +275 -0
  111. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +294 -0
  112. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +1384 -0
  113. package/vendor/quiche/src/recovery/mod.rs +3086 -0
  114. package/vendor/quiche/src/recovery/rtt.rs +152 -0
  115. package/vendor/quiche/src/stream/mod.rs +2210 -0
  116. package/vendor/quiche/src/stream/recv_buf.rs +1236 -0
  117. package/vendor/quiche/src/stream/send_buf.rs +849 -0
  118. package/vendor/quiche/src/test_utils.rs +681 -0
  119. package/vendor/quiche/src/tests.rs +12922 -0
  120. package/vendor/quiche/src/tls/boringssl.rs +375 -0
  121. package/vendor/quiche/src/tls/mod.rs +1245 -0
  122. package/vendor/quiche/src/transport_params.rs +628 -0
@@ -0,0 +1,288 @@
1
+ // Copyright (C) 2019, Cloudflare, Inc.
2
+ // All rights reserved.
3
+ //
4
+ // Redistribution and use in source and binary forms, with or without
5
+ // modification, are permitted provided that the following conditions are
6
+ // met:
7
+ //
8
+ // * Redistributions of source code must retain the above copyright notice,
9
+ // this list of conditions and the following disclaimer.
10
+ //
11
+ // * Redistributions in binary form must reproduce the above copyright
12
+ // notice, this list of conditions and the following disclaimer in the
13
+ // documentation and/or other materials provided with the distribution.
14
+ //
15
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16
+ // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19
+ // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20
+ // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
+ // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22
+ // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23
+ // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24
+ // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
+ // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
+
27
+ use super::Error;
28
+ use super::Result;
29
+
30
+ use crate::h3::Header;
31
+
32
+ use super::INDEXED;
33
+ use super::INDEXED_WITH_POST_BASE;
34
+ use super::LITERAL;
35
+ use super::LITERAL_WITH_NAME_REF;
36
+
37
+ #[derive(Clone, Copy, Debug, PartialEq)]
38
+ enum Representation {
39
+ Indexed,
40
+ IndexedWithPostBase,
41
+ Literal,
42
+ LiteralWithNameRef,
43
+ LiteralWithPostBase,
44
+ }
45
+
46
+ impl Representation {
47
+ pub fn from_byte(b: u8) -> Representation {
48
+ if b & INDEXED == INDEXED {
49
+ return Representation::Indexed;
50
+ }
51
+
52
+ if b & LITERAL_WITH_NAME_REF == LITERAL_WITH_NAME_REF {
53
+ return Representation::LiteralWithNameRef;
54
+ }
55
+
56
+ if b & LITERAL == LITERAL {
57
+ return Representation::Literal;
58
+ }
59
+
60
+ if b & INDEXED_WITH_POST_BASE == INDEXED_WITH_POST_BASE {
61
+ return Representation::IndexedWithPostBase;
62
+ }
63
+
64
+ Representation::LiteralWithPostBase
65
+ }
66
+ }
67
+
68
+ /// A QPACK decoder.
69
+ #[derive(Default)]
70
+ pub struct Decoder {}
71
+
72
+ impl Decoder {
73
+ /// Creates a new QPACK decoder.
74
+ pub fn new() -> Decoder {
75
+ Decoder::default()
76
+ }
77
+
78
+ /// Processes control instructions from the encoder.
79
+ pub fn control(&mut self, _buf: &mut [u8]) -> Result<()> {
80
+ // TODO: process control instructions
81
+ Ok(())
82
+ }
83
+
84
+ /// Decodes a QPACK header block into a list of headers.
85
+ pub fn decode(&mut self, buf: &[u8], max_size: u64) -> Result<Vec<Header>> {
86
+ let mut b = octets::Octets::with_slice(buf);
87
+
88
+ let mut out = Vec::new();
89
+
90
+ let mut left = max_size;
91
+
92
+ let req_insert_count = decode_int(&mut b, 8)?;
93
+ let base = decode_int(&mut b, 7)?;
94
+
95
+ trace!("Header count={req_insert_count} base={base}");
96
+
97
+ while b.cap() > 0 {
98
+ let first = b.peek_u8()?;
99
+
100
+ match Representation::from_byte(first) {
101
+ Representation::Indexed => {
102
+ const STATIC: u8 = 0x40;
103
+
104
+ let s = first & STATIC == STATIC;
105
+ let index = decode_int(&mut b, 6)?;
106
+
107
+ trace!("Indexed index={index} static={s}");
108
+
109
+ if !s {
110
+ // TODO: implement dynamic table
111
+ return Err(Error::InvalidHeaderValue);
112
+ }
113
+
114
+ let (name, value) = lookup_static(index)?;
115
+
116
+ left = left
117
+ .checked_sub((name.len() + value.len()) as u64)
118
+ .ok_or(Error::HeaderListTooLarge)?;
119
+
120
+ let hdr = Header::new(name, value);
121
+ out.push(hdr);
122
+ },
123
+
124
+ Representation::IndexedWithPostBase => {
125
+ let index = decode_int(&mut b, 4)?;
126
+
127
+ trace!("Indexed With Post Base index={index}");
128
+
129
+ // TODO: implement dynamic table
130
+ return Err(Error::InvalidHeaderValue);
131
+ },
132
+
133
+ Representation::Literal => {
134
+ let name_huff = b.as_ref()[0] & 0x08 == 0x08;
135
+ let name_len = decode_int(&mut b, 3)? as usize;
136
+
137
+ let mut name = b.get_bytes(name_len)?;
138
+
139
+ let name = if name_huff {
140
+ name.get_huffman_decoded()?
141
+ } else {
142
+ name.to_vec()
143
+ };
144
+
145
+ let name = name.to_vec();
146
+ let value = decode_str(&mut b)?;
147
+
148
+ trace!(
149
+ "Literal Without Name Reference name={name:?} value={value:?}",
150
+ );
151
+
152
+ left = left
153
+ .checked_sub((name.len() + value.len()) as u64)
154
+ .ok_or(Error::HeaderListTooLarge)?;
155
+
156
+ // Instead of calling Header::new(), create Header directly
157
+ // from `name` and `value`, which are already String.
158
+ let hdr = Header(name, value);
159
+ out.push(hdr);
160
+ },
161
+
162
+ Representation::LiteralWithNameRef => {
163
+ const STATIC: u8 = 0x10;
164
+
165
+ let s = first & STATIC == STATIC;
166
+ let name_idx = decode_int(&mut b, 4)?;
167
+ let value = decode_str(&mut b)?;
168
+
169
+ trace!(
170
+ "Literal name_idx={name_idx} static={s} value={value:?}"
171
+ );
172
+
173
+ if !s {
174
+ // TODO: implement dynamic table
175
+ return Err(Error::InvalidHeaderValue);
176
+ }
177
+
178
+ let (name, _) = lookup_static(name_idx)?;
179
+
180
+ left = left
181
+ .checked_sub((name.len() + value.len()) as u64)
182
+ .ok_or(Error::HeaderListTooLarge)?;
183
+
184
+ // Instead of calling Header::new(), create Header directly
185
+ // from `value`, which is already String, but clone `name`
186
+ // as it is just a reference.
187
+ let hdr = Header(name.to_vec(), value);
188
+ out.push(hdr);
189
+ },
190
+
191
+ Representation::LiteralWithPostBase => {
192
+ trace!("Literal With Post Base");
193
+
194
+ // TODO: implement dynamic table
195
+ return Err(Error::InvalidHeaderValue);
196
+ },
197
+ }
198
+ }
199
+
200
+ Ok(out)
201
+ }
202
+ }
203
+
204
+ fn lookup_static(idx: u64) -> Result<(&'static [u8], &'static [u8])> {
205
+ if idx >= super::static_table::STATIC_DECODE_TABLE.len() as u64 {
206
+ return Err(Error::InvalidStaticTableIndex);
207
+ }
208
+
209
+ Ok(super::static_table::STATIC_DECODE_TABLE[idx as usize])
210
+ }
211
+
212
+ fn decode_int(b: &mut octets::Octets, prefix: usize) -> Result<u64> {
213
+ let mask = 2u64.pow(prefix as u32) - 1;
214
+
215
+ let mut val = u64::from(b.get_u8()?);
216
+ val &= mask;
217
+
218
+ if val < mask {
219
+ return Ok(val);
220
+ }
221
+
222
+ let mut shift = 0;
223
+
224
+ while b.cap() > 0 {
225
+ let byte = b.get_u8()?;
226
+
227
+ let inc = u64::from(byte & 0x7f)
228
+ .checked_shl(shift)
229
+ .ok_or(Error::BufferTooShort)?;
230
+
231
+ val = val.checked_add(inc).ok_or(Error::BufferTooShort)?;
232
+
233
+ shift += 7;
234
+
235
+ if byte & 0x80 == 0 {
236
+ return Ok(val);
237
+ }
238
+ }
239
+
240
+ Err(Error::BufferTooShort)
241
+ }
242
+
243
+ fn decode_str(b: &mut octets::Octets) -> Result<Vec<u8>> {
244
+ let first = b.peek_u8()?;
245
+
246
+ let huff = first & 0x80 == 0x80;
247
+
248
+ let len = decode_int(b, 7)? as usize;
249
+
250
+ let mut val = b.get_bytes(len)?;
251
+
252
+ let val = if huff {
253
+ val.get_huffman_decoded()?
254
+ } else {
255
+ val.to_vec()
256
+ };
257
+
258
+ Ok(val)
259
+ }
260
+
261
+ #[cfg(test)]
262
+ mod tests {
263
+ use super::*;
264
+
265
+ #[test]
266
+ fn decode_int1() {
267
+ let encoded = [0b01010, 0x02];
268
+ let mut b = octets::Octets::with_slice(&encoded);
269
+
270
+ assert_eq!(decode_int(&mut b, 5), Ok(10));
271
+ }
272
+
273
+ #[test]
274
+ fn decode_int2() {
275
+ let encoded = [0b11111, 0b10011010, 0b00001010];
276
+ let mut b = octets::Octets::with_slice(&encoded);
277
+
278
+ assert_eq!(decode_int(&mut b, 5), Ok(1337));
279
+ }
280
+
281
+ #[test]
282
+ fn decode_int3() {
283
+ let encoded = [0b101010];
284
+ let mut b = octets::Octets::with_slice(&encoded);
285
+
286
+ assert_eq!(decode_int(&mut b, 8), Ok(42));
287
+ }
288
+ }
@@ -0,0 +1,235 @@
1
+ // Copyright (C) 2019, Cloudflare, Inc.
2
+ // All rights reserved.
3
+ //
4
+ // Redistribution and use in source and binary forms, with or without
5
+ // modification, are permitted provided that the following conditions are
6
+ // met:
7
+ //
8
+ // * Redistributions of source code must retain the above copyright notice,
9
+ // this list of conditions and the following disclaimer.
10
+ //
11
+ // * Redistributions in binary form must reproduce the above copyright
12
+ // notice, this list of conditions and the following disclaimer in the
13
+ // documentation and/or other materials provided with the distribution.
14
+ //
15
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16
+ // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19
+ // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20
+ // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
+ // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22
+ // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23
+ // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24
+ // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
+ // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
+
27
+ use super::Result;
28
+
29
+ use crate::h3::NameValue;
30
+
31
+ use super::INDEXED;
32
+ use super::LITERAL;
33
+ use super::LITERAL_WITH_NAME_REF;
34
+
35
+ /// A QPACK encoder.
36
+ #[derive(Default)]
37
+ pub struct Encoder {}
38
+
39
+ impl Encoder {
40
+ /// Creates a new QPACK encoder.
41
+ pub fn new() -> Encoder {
42
+ Encoder::default()
43
+ }
44
+
45
+ /// Encodes a list of headers into a QPACK header block.
46
+ pub fn encode<T: NameValue>(
47
+ &mut self, headers: &[T], out: &mut [u8],
48
+ ) -> Result<usize> {
49
+ let mut b = octets::OctetsMut::with_slice(out);
50
+
51
+ // Required Insert Count.
52
+ encode_int(0, 0, 8, &mut b)?;
53
+
54
+ // Base.
55
+ encode_int(0, 0, 7, &mut b)?;
56
+
57
+ for h in headers {
58
+ match lookup_static(h) {
59
+ Some((idx, true)) => {
60
+ const STATIC: u8 = 0x40;
61
+
62
+ // Encode as statically indexed.
63
+ encode_int(idx, INDEXED | STATIC, 6, &mut b)?;
64
+ },
65
+
66
+ Some((idx, false)) => {
67
+ const STATIC: u8 = 0x10;
68
+
69
+ // Encode value as literal with static name reference.
70
+ encode_int(idx, LITERAL_WITH_NAME_REF | STATIC, 4, &mut b)?;
71
+ encode_str::<false>(h.value(), 0, 7, &mut b)?;
72
+ },
73
+
74
+ None => {
75
+ // Encode as fully literal.
76
+
77
+ encode_str::<true>(h.name(), LITERAL, 3, &mut b)?;
78
+ encode_str::<false>(h.value(), 0, 7, &mut b)?;
79
+ },
80
+ };
81
+ }
82
+
83
+ Ok(b.off())
84
+ }
85
+ }
86
+
87
+ fn lookup_static<T: NameValue>(h: &T) -> Option<(u64, bool)> {
88
+ // Fetch the right encoding table for this header length.
89
+ let table_for_len =
90
+ super::static_table::STATIC_ENCODE_TABLE.get(h.name().len())?;
91
+
92
+ // Similar to [`eq_ignore_ascii_case`], but only lowercases the second
93
+ // operand, as the entries in the table are already lower cased.
94
+ let cmp_lowercase = |a: &[u8], b: &[u8]| {
95
+ std::iter::zip(a, b).all(|(a, b)| a.eq(&b.to_ascii_lowercase()))
96
+ };
97
+
98
+ for (name, values) in table_for_len.iter() {
99
+ // Match header name first.
100
+ if cmp_lowercase(name, h.name()) {
101
+ // Second iterate over possible values for the header.
102
+ for (value, enc) in values.iter() {
103
+ // Match header value.
104
+ if value.is_empty() {
105
+ return Some((*enc, false));
106
+ }
107
+
108
+ if h.value() == *value {
109
+ return Some((*enc, true));
110
+ }
111
+ }
112
+ // Only matched the header, not the value.
113
+ return Some((values.first()?.1, false));
114
+ }
115
+ }
116
+
117
+ None
118
+ }
119
+
120
+ pub fn encode_int(
121
+ mut v: u64, first: u8, prefix: usize, b: &mut octets::OctetsMut,
122
+ ) -> Result<()> {
123
+ let mask = 2u64.pow(prefix as u32) - 1;
124
+
125
+ // Encode I on N bits.
126
+ if v < mask {
127
+ b.put_u8(first | v as u8)?;
128
+ return Ok(());
129
+ }
130
+
131
+ // Encode (2^N - 1) on N bits.
132
+ b.put_u8(first | mask as u8)?;
133
+
134
+ v -= mask;
135
+
136
+ while v >= 128 {
137
+ // Encode (I % 128 + 128) on 8 bits.
138
+ b.put_u8((v % 128 + 128) as u8)?;
139
+
140
+ v >>= 7;
141
+ }
142
+
143
+ // Encode I on 8 bits.
144
+ b.put_u8(v as u8)?;
145
+
146
+ Ok(())
147
+ }
148
+
149
+ #[inline]
150
+ pub fn encode_str<const LOWER_CASE: bool>(
151
+ v: &[u8], first: u8, prefix: usize, b: &mut octets::OctetsMut,
152
+ ) -> Result<()> {
153
+ // Huffman-encoding generally saves space but in some cases it doesn't, for
154
+ // those just encode the literal string.
155
+ match octets::huffman_encoding_len::<LOWER_CASE>(v) {
156
+ Ok(len) => {
157
+ encode_int(len as u64, first | (1 << prefix), prefix, b)?;
158
+ b.put_huffman_encoded::<LOWER_CASE>(v)?;
159
+ },
160
+
161
+ Err(_) => {
162
+ encode_int(v.len() as u64, first, prefix, b)?;
163
+ if LOWER_CASE {
164
+ b.put_bytes(&v.to_ascii_lowercase())?;
165
+ } else {
166
+ b.put_bytes(v)?;
167
+ }
168
+ },
169
+ }
170
+
171
+ Ok(())
172
+ }
173
+
174
+ #[cfg(test)]
175
+ mod tests {
176
+ use super::*;
177
+
178
+ #[test]
179
+ fn encode_int1() {
180
+ let expected = [0b01010];
181
+ let mut encoded = [0; 1];
182
+ let mut b = octets::OctetsMut::with_slice(&mut encoded);
183
+
184
+ assert!(encode_int(10, 0, 5, &mut b).is_ok());
185
+
186
+ assert_eq!(expected, encoded);
187
+ }
188
+
189
+ #[test]
190
+ fn encode_int2() {
191
+ let expected = [0b11111, 0b10011010, 0b00001010];
192
+ let mut encoded = [0; 3];
193
+ let mut b = octets::OctetsMut::with_slice(&mut encoded);
194
+
195
+ assert!(encode_int(1337, 0, 5, &mut b).is_ok());
196
+
197
+ assert_eq!(expected, encoded);
198
+ }
199
+
200
+ #[test]
201
+ fn encode_int3() {
202
+ let expected = [0b101010];
203
+ let mut encoded = [0; 1];
204
+ let mut b = octets::OctetsMut::with_slice(&mut encoded);
205
+
206
+ assert!(encode_int(42, 0, 8, &mut b).is_ok());
207
+
208
+ assert_eq!(expected, encoded);
209
+ }
210
+
211
+ #[test]
212
+ fn encode_static_header() {
213
+ let mut encoded = [0; 3];
214
+ Encoder::default()
215
+ .encode(&[(b":method", b"GET")], &mut encoded)
216
+ .unwrap();
217
+ assert_eq!(encoded, [0, 0, INDEXED | 0x40 | 17]);
218
+ }
219
+
220
+ #[test]
221
+ fn encode_static_header_name_only() {
222
+ let mut encoded = [0; 11];
223
+ let mut expected = [0; 11];
224
+ let mut buf = octets::OctetsMut::with_slice(&mut expected[..]);
225
+ buf.put_u16(0).unwrap();
226
+ buf.put_u8(LITERAL_WITH_NAME_REF | 0x10 | 15).unwrap();
227
+ buf.put_u8(0).unwrap();
228
+ encode_str::<false>(b"FORGET", 0, 7, &mut buf).unwrap();
229
+
230
+ Encoder::default()
231
+ .encode(&[(b":method", b"FORGET")], &mut encoded)
232
+ .unwrap();
233
+ assert_eq!(encoded, expected);
234
+ }
235
+ }