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,80 @@
1
+ # recovery/ -- Loss Detection & Congestion Control
2
+
3
+ ## OVERVIEW
4
+
5
+ QUIC loss detection and congestion control per RFC 9002. Two parallel CC
6
+ implementations coexist: `congestion/` (legacy Reno/CUBIC) and `gcongestion/`
7
+ (next-gen BBR2 ported from google/quiche). `Recovery` enum dispatches between
8
+ `LegacyRecovery` and `GRecovery` via `enum_dispatch` over the `RecoveryOps`
9
+ trait (40+ methods).
10
+
11
+ ## STRUCTURE
12
+
13
+ ```
14
+ mod.rs Recovery enum, RecoveryOps trait, CongestionControlAlgorithm,
15
+ Sent, ReleaseTime/ReleaseDecision, RecoveryConfig, constants
16
+ bandwidth.rs Bandwidth newtype
17
+ bytes_in_flight.rs Bytes-in-flight tracking
18
+ rtt.rs RTT estimation
19
+
20
+ congestion/ Legacy CC (Reno, CUBIC)
21
+ mod.rs CongestionControlOps vtable struct, Congestion state
22
+ recovery.rs LegacyRecovery impl of RecoveryOps, Acked struct
23
+ reno.rs Static RENO: CongestionControlOps
24
+ cubic.rs Static CUBIC: CongestionControlOps
25
+ delivery_rate.rs Delivery rate sampling
26
+ hystart.rs HyStart slow-start exit
27
+ prr.rs Proportional Rate Reduction
28
+ test_sender.rs Test-only CC sender
29
+
30
+ gcongestion/ Next-gen CC (BBR2)
31
+ mod.rs CongestionControl trait, Acked struct, BbrParams (#[doc(hidden)])
32
+ recovery.rs GRecovery impl of RecoveryOps
33
+ pacer.rs Token-bucket pacer
34
+ bbr2.rs BBR2 top-level + Bbr2CongestionControl
35
+ bbr2/ BBR2 state machine substates
36
+ mode.rs Mode enum (Startup, Drain, ProbeBw, ProbeRtt)
37
+ startup.rs Startup mode
38
+ drain.rs Drain mode
39
+ probe_bw.rs ProbeBW mode (bandwidth probing cycles)
40
+ probe_rtt.rs ProbeRTT mode (min RTT measurement)
41
+ network_model.rs Bandwidth/RTT model, BbrParams application
42
+ bbr.rs BBR (v1, not actively used)
43
+ ```
44
+
45
+ ## WHERE TO LOOK
46
+
47
+ | Task | File | Notes |
48
+ |------|------|-------|
49
+ | Add/change CC algorithm | `congestion/mod.rs` or `gcongestion/mod.rs` | Different dispatch patterns |
50
+ | Modify loss detection | `congestion/recovery.rs` or `gcongestion/recovery.rs` | Parallel impls |
51
+ | Shared trait surface | `mod.rs:183-320` | `RecoveryOps` -- both impls must satisfy |
52
+ | Algorithm selection | `mod.rs:365` | `CongestionControlAlgorithm` enum, `#[repr(C)]` for FFI |
53
+ | BBR2 tuning | `gcongestion/bbr2/network_model.rs` | `BbrParams` applied here |
54
+ | Pacing | `gcongestion/pacer.rs`, `mod.rs:691` | `ReleaseTime`, `ReleaseDecision` |
55
+ | Per-packet metadata | `mod.rs:394` | `Sent` struct |
56
+ | qlog integration | grep `#[cfg(feature = "qlog")]` | Gated throughout both impls |
57
+
58
+ ## ANTI-PATTERNS
59
+
60
+ - **Two `Acked` structs** at `congestion/recovery.rs:1079` and `gcongestion/mod.rs:49`.
61
+ NOT unified. Do NOT create a third.
62
+ - **FIXME stubs**: Some `RecoveryOps` methods only apply to one impl. Both sides
63
+ have `// FIXME only used by {congestion,gcongestion}` stubs that return
64
+ defaults. Do not proliferate; prefer narrowing the shared trait.
65
+ - **`congestion/` uses C-like vtable** (`CongestionControlOps` with static fn
66
+ pointers: `RENO`, `CUBIC`). `gcongestion/` uses trait objects
67
+ (`CongestionControl` trait). Do not mix dispatch styles.
68
+ - **`BbrParams` is `#[doc(hidden)]`** and experimental. Do not stabilize or
69
+ expose without explicit intent.
70
+ - **Many `#[cfg(test)]` accessors** on `RecoveryOps` (lines 200-297). Test-only;
71
+ do not call from production code.
72
+
73
+ ## NOTES
74
+
75
+ - Constants cite RFC 9002: `INITIAL_TIME_THRESHOLD = 9.0/8.0`, `GRANULARITY = 1ms`.
76
+ - `CongestionControlAlgorithm` values: Reno=0, CUBIC=1, Bbr2Gcongestion=4. Gap is intentional (removed variants).
77
+ - `Recovery::new_with_config` tries `GRecovery::new` first; falls back to `LegacyRecovery` if algo is Reno/CUBIC.
78
+ - `bbr2/` is a deeply nested state machine -- changes require understanding all six substates.
79
+ - `enable_relaxed_loss_threshold` experiment adjusts time thresholds dynamically on spurious loss.
80
+ - `gcongestion/bbr.rs` is BBRv1 -- mostly vestigial alongside BBR2.
@@ -0,0 +1,565 @@
1
+ // Copyright (C) 2023, 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 std::time::Duration;
28
+
29
+ const NUM_MILLIS_PER_SECOND: u64 = 1000;
30
+ const NUM_MICROS_PER_MILLI: u64 = 1000;
31
+ const NUM_MICROS_PER_SECOND: u64 = NUM_MICROS_PER_MILLI * NUM_MILLIS_PER_SECOND;
32
+ const NUM_NANOS_PER_SECOND: u64 = 1000 * NUM_MICROS_PER_SECOND;
33
+
34
+ #[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Copy)]
35
+ pub struct Bandwidth {
36
+ bits_per_second: u64,
37
+ }
38
+
39
+ impl std::ops::Mul<f64> for Bandwidth {
40
+ type Output = Bandwidth;
41
+
42
+ fn mul(self, rhs: f64) -> Self::Output {
43
+ Bandwidth {
44
+ bits_per_second: (self.bits_per_second as f64 * rhs).round() as u64,
45
+ }
46
+ }
47
+ }
48
+
49
+ impl std::ops::Mul<f32> for Bandwidth {
50
+ type Output = Bandwidth;
51
+
52
+ fn mul(self, rhs: f32) -> Self::Output {
53
+ self * rhs as f64
54
+ }
55
+ }
56
+
57
+ impl std::ops::Sub<Bandwidth> for Bandwidth {
58
+ type Output = Option<Bandwidth>;
59
+
60
+ fn sub(self, rhs: Bandwidth) -> Self::Output {
61
+ self.bits_per_second
62
+ .checked_sub(rhs.bits_per_second)
63
+ .map(|bps| Bandwidth {
64
+ bits_per_second: bps,
65
+ })
66
+ }
67
+ }
68
+
69
+ impl std::ops::Add<Bandwidth> for Bandwidth {
70
+ type Output = Bandwidth;
71
+
72
+ fn add(self, rhs: Bandwidth) -> Self::Output {
73
+ Bandwidth {
74
+ bits_per_second: self.bits_per_second.add(rhs.bits_per_second),
75
+ }
76
+ }
77
+ }
78
+
79
+ impl std::ops::Mul<Duration> for Bandwidth {
80
+ type Output = u64;
81
+
82
+ fn mul(self, rhs: Duration) -> Self::Output {
83
+ self.to_bytes_per_period(rhs)
84
+ }
85
+ }
86
+
87
+ impl Bandwidth {
88
+ pub const fn from_bytes_and_time_delta(
89
+ bytes: usize, time_delta: Duration,
90
+ ) -> Self {
91
+ if bytes == 0 {
92
+ return Bandwidth { bits_per_second: 0 };
93
+ }
94
+
95
+ let mut nanos = time_delta.as_nanos() as u64;
96
+ if nanos == 0 {
97
+ nanos = 1;
98
+ }
99
+
100
+ let num_nano_bits = 8 * bytes as u64 * NUM_NANOS_PER_SECOND;
101
+ if num_nano_bits < nanos {
102
+ return Bandwidth { bits_per_second: 1 };
103
+ }
104
+
105
+ Bandwidth {
106
+ bits_per_second: num_nano_bits / nanos,
107
+ }
108
+ }
109
+
110
+ #[allow(dead_code)]
111
+ pub const fn from_bytes_per_second(bytes_per_second: u64) -> Self {
112
+ Bandwidth {
113
+ bits_per_second: bytes_per_second * 8,
114
+ }
115
+ }
116
+
117
+ #[allow(dead_code)]
118
+ pub const fn to_bits_per_second(self) -> u64 {
119
+ self.bits_per_second
120
+ }
121
+
122
+ pub const fn to_bytes_per_second(self) -> u64 {
123
+ self.bits_per_second / 8
124
+ }
125
+
126
+ pub const fn from_kbits_per_second(k_bits_per_second: u64) -> Self {
127
+ Bandwidth {
128
+ bits_per_second: k_bits_per_second * 1_000,
129
+ }
130
+ }
131
+
132
+ #[allow(dead_code)]
133
+ pub const fn from_mbits_per_second(m_bits_per_second: u64) -> Self {
134
+ Bandwidth::from_kbits_per_second(m_bits_per_second * 1_000)
135
+ }
136
+
137
+ /// Returns a sentinel representing infinite bandwidth.
138
+ pub const fn infinite() -> Self {
139
+ Bandwidth {
140
+ bits_per_second: u64::MAX,
141
+ }
142
+ }
143
+
144
+ pub const fn zero() -> Self {
145
+ Bandwidth { bits_per_second: 0 }
146
+ }
147
+
148
+ /// Returns the time to transfer `bytes` at this bandwidth.
149
+ ///
150
+ /// Returns `Duration::ZERO` for infinite or zero bandwidth.
151
+ /// Saturates to `Duration::from_nanos(u64::MAX)` if the
152
+ /// calculation would overflow.
153
+ pub fn transfer_time(&self, bytes: u64) -> Duration {
154
+ // Handle infinite bandwidth sentinel: transfer is instantaneous
155
+ if self.bits_per_second == u64::MAX {
156
+ return Duration::ZERO;
157
+ }
158
+
159
+ if self.bits_per_second == 0 {
160
+ return Duration::ZERO;
161
+ }
162
+
163
+ // Fast path: try u64 arithmetic first. At typical packet sizes
164
+ // (< 10 KB) and bandwidths, this won't overflow.
165
+ if let Some(nanos) = bytes.checked_mul(8 * NUM_NANOS_PER_SECOND) {
166
+ return Duration::from_nanos(nanos / self.bits_per_second);
167
+ }
168
+
169
+ // Slow path: use u128 for intermediate calculation to avoid overflow.
170
+ // At very large byte counts, bytes * 8 * NUM_NANOS_PER_SECOND can
171
+ // overflow u64.
172
+ let nanos = (bytes as u128) * (8 * NUM_NANOS_PER_SECOND) as u128;
173
+ let nanos = nanos / (self.bits_per_second as u128);
174
+
175
+ // Saturate to Duration::MAX if result exceeds u64 range.
176
+ Duration::from_nanos(nanos.min(u64::MAX as u128) as u64)
177
+ }
178
+
179
+ /// Returns the number of bytes that can be sent in
180
+ /// `time_period` at this bandwidth.
181
+ ///
182
+ /// Returns `u64::MAX` for infinite bandwidth (unless
183
+ /// `time_period` is zero). Saturates to `u64::MAX` if the
184
+ /// calculation would overflow.
185
+ pub fn to_bytes_per_period(self, time_period: Duration) -> u64 {
186
+ // Handle infinite bandwidth sentinel.
187
+ if self.bits_per_second == u64::MAX {
188
+ if time_period != Duration::ZERO {
189
+ return u64::MAX;
190
+ } else {
191
+ return 0;
192
+ }
193
+ }
194
+
195
+ // Fast path: try u64 arithmetic first. At typical bandwidths (< 10
196
+ // Gbps) and short time periods (< 1 second), this won't overflow.
197
+ if let Ok(time_nanos) = u64::try_from(time_period.as_nanos()) {
198
+ if let Some(bits) = self.bits_per_second.checked_mul(time_nanos) {
199
+ return bits / (8 * NUM_NANOS_PER_SECOND);
200
+ }
201
+ }
202
+
203
+ // Slow path: use u128 for intermediate calculation to avoid overflow.
204
+ // At high bandwidths (e.g., 10+ Gbps) with non-trivial time periods,
205
+ // bits_per_second * time_period.as_nanos() can overflow u64.
206
+ let time_nanos = time_period.as_nanos();
207
+ let bits = (self.bits_per_second as u128).saturating_mul(time_nanos);
208
+ let bytes = bits / (8 * NUM_NANOS_PER_SECOND) as u128;
209
+
210
+ // Saturate to u64::MAX if result exceeds u64 range.
211
+ bytes.min(u64::MAX as u128) as u64
212
+ }
213
+ }
214
+
215
+ impl std::fmt::Debug for Bandwidth {
216
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
217
+ match self.bits_per_second {
218
+ x if x < 1_000_000 => write!(f, "{:.2} Kbps", x as f64 / 1_000.),
219
+ x if x < 1_000_000_000 => {
220
+ write!(f, "{:.2} Mbps", x as f64 / 1_000_000.)
221
+ },
222
+ x => write!(f, "{:.2} Gbps", x as f64 / 1_000_000_000.),
223
+ }
224
+ }
225
+ }
226
+
227
+ #[cfg(test)]
228
+ mod tests {
229
+ use super::*;
230
+
231
+ #[test]
232
+ fn constructors() {
233
+ // Internal representation is bits per second.
234
+ assert_eq!(Bandwidth::from_bytes_per_second(100).bits_per_second, 800);
235
+ let bw = Bandwidth::from_bytes_per_second(100);
236
+ assert_eq!(bw.to_bits_per_second(), 800);
237
+ assert_eq!(bw.to_bytes_per_second(), 100);
238
+
239
+ // kbits == 1000 bits
240
+ assert_eq!(
241
+ Bandwidth::from_kbits_per_second(100).bits_per_second,
242
+ 100_000
243
+ );
244
+
245
+ // mbits == 1000,000 bits
246
+ assert_eq!(
247
+ Bandwidth::from_mbits_per_second(100).bits_per_second,
248
+ 100_000_000
249
+ );
250
+
251
+ assert_eq!(Bandwidth::infinite().bits_per_second, u64::MAX);
252
+ assert_eq!(Bandwidth::zero().bits_per_second, 0);
253
+ }
254
+
255
+ #[test]
256
+ fn arithmetic_ops() {
257
+ let bw_1k = Bandwidth::from_kbits_per_second(1);
258
+ let bw_5k = Bandwidth::from_kbits_per_second(5);
259
+ let bw_6k = Bandwidth::from_kbits_per_second(6);
260
+
261
+ // Addition
262
+ assert_eq!(bw_1k + bw_5k, bw_6k);
263
+
264
+ // Subtraction
265
+ assert_eq!(bw_6k - bw_5k, Some(bw_1k));
266
+ assert_eq!(bw_6k - bw_6k, Some(Bandwidth::zero()));
267
+
268
+ // Negative bw is not defined.
269
+ assert_eq!(bw_1k - bw_5k, None);
270
+
271
+ // Multiplication by scalars
272
+ assert_eq!(bw_1k * 6.0f64, bw_6k);
273
+ assert_eq!(bw_1k * 6.0f32, bw_6k);
274
+ assert_eq!(bw_5k * 0.0, Bandwidth::zero());
275
+ assert_eq!(bw_5k * 1.0, bw_5k);
276
+
277
+ // Multiplication saturates on overflow and underflow.
278
+ assert_eq!(Bandwidth::infinite() * -1.0, Bandwidth::zero());
279
+ assert_eq!((Bandwidth::infinite() * 2.0f64).bits_per_second, u64::MAX);
280
+
281
+ // Multiplication rounds up.
282
+ assert_eq!(
283
+ (Bandwidth::infinite() * 0.5f64).bits_per_second,
284
+ u64::MAX / 2 + 1
285
+ );
286
+ }
287
+
288
+ #[test]
289
+ fn from_bytes_and_time_delta() {
290
+ assert_eq!(
291
+ Bandwidth::from_bytes_and_time_delta(10, Duration::from_millis(1000))
292
+ .bits_per_second,
293
+ 80
294
+ );
295
+ assert_eq!(
296
+ Bandwidth::from_bytes_and_time_delta(10, Duration::from_millis(100))
297
+ .bits_per_second,
298
+ 800
299
+ );
300
+ assert_eq!(
301
+ Bandwidth::from_bytes_and_time_delta(
302
+ 100,
303
+ Duration::from_millis(1000)
304
+ )
305
+ .bits_per_second,
306
+ 800
307
+ );
308
+ }
309
+
310
+ #[test]
311
+ fn transfer_time() {
312
+ let one_kbit_sec = Bandwidth::from_kbits_per_second(1);
313
+ assert_eq!(one_kbit_sec.transfer_time(0), Duration::ZERO);
314
+ assert_eq!(one_kbit_sec.transfer_time(100), Duration::from_millis(800));
315
+ }
316
+
317
+ // Test that large byte values that would overflow u64 are handled
318
+ // correctly using u128 arithmetic.
319
+ #[test]
320
+ fn transfer_time_overflow() {
321
+ let low_bandwidth = Bandwidth::from_kbits_per_second(1);
322
+
323
+ // This value would overflow: u64::MAX * 8 * NUM_MICROS_PER_SECOND
324
+ // which exceeds u64::MAX.
325
+ let large_bytes = u64::MAX;
326
+ let result = low_bandwidth.transfer_time(large_bytes);
327
+
328
+ // At 1 kbit/s = 125 bytes/s, transferring u64::MAX bytes would take
329
+ // an astronomically long time. Result should saturate to Duration::MAX
330
+ // (u64::MAX nanoseconds).
331
+ assert_eq!(result, Duration::from_nanos(u64::MAX));
332
+
333
+ // Test a more realistic large value: 10 GiB at 1 Gbps should work.
334
+ let one_gbps = Bandwidth::from_mbits_per_second(1_000); // 1 Gbps
335
+ let ten_gib = 10 * 1024 * 1024 * 1024;
336
+ // 10 GiB * 8 bits/byte / 1 Gbit/s = 85.899... seconds
337
+ let expected = Duration::from_nanos(85_899_345_920);
338
+ assert_eq!(one_gbps.transfer_time(ten_gib), expected);
339
+ }
340
+
341
+ #[test]
342
+ fn transfer_time_infinite() {
343
+ // Infinite bandwidth should have zero transfer time (instantaneous)
344
+ let inf = Bandwidth::infinite();
345
+
346
+ // Zero bytes
347
+ assert_eq!(inf.transfer_time(0), Duration::ZERO);
348
+
349
+ // Small transfers
350
+ assert_eq!(inf.transfer_time(1), Duration::ZERO);
351
+ assert_eq!(inf.transfer_time(100), Duration::ZERO);
352
+ assert_eq!(inf.transfer_time(1024), Duration::ZERO);
353
+
354
+ // Large transfers
355
+ assert_eq!(inf.transfer_time(1_000_000), Duration::ZERO);
356
+ assert_eq!(inf.transfer_time(u64::MAX), Duration::ZERO);
357
+ }
358
+
359
+ #[test]
360
+ fn to_bytes_per_period() {
361
+ let one_kbit_sec = Bandwidth::from_kbits_per_second(1);
362
+ assert_eq!(
363
+ one_kbit_sec.to_bytes_per_period(Duration::from_millis(10_000)),
364
+ 1250
365
+ );
366
+ assert_eq!(
367
+ one_kbit_sec.to_bytes_per_period(Duration::from_millis(1000)),
368
+ 125
369
+ );
370
+ assert_eq!(
371
+ one_kbit_sec.to_bytes_per_period(Duration::from_millis(100)),
372
+ 12
373
+ );
374
+ assert_eq!(
375
+ one_kbit_sec.to_bytes_per_period(Duration::from_millis(10)),
376
+ 1
377
+ );
378
+ assert_eq!(
379
+ one_kbit_sec.to_bytes_per_period(Duration::from_millis(1)),
380
+ 0
381
+ );
382
+
383
+ // Mul<Duration> implementation.
384
+ assert_eq!(one_kbit_sec * Duration::from_millis(10_000), 1250);
385
+ }
386
+
387
+ #[test]
388
+ fn to_bytes_per_period_high_bandwidth() {
389
+ // 10 Gbps with 1 second would overflow u64 in the old implementation.
390
+ let ten_gbps = Bandwidth::from_mbits_per_second(10_000);
391
+ assert_eq!(
392
+ ten_gbps.to_bytes_per_period(Duration::from_secs(1)),
393
+ 1_250_000_000
394
+ );
395
+
396
+ // 100 Gbps with 100ms.
397
+ let hundred_gbps = Bandwidth::from_mbits_per_second(100_000);
398
+ assert_eq!(
399
+ hundred_gbps.to_bytes_per_period(Duration::from_millis(100)),
400
+ 1_250_000_000
401
+ );
402
+
403
+ // 1 Tbps with 10ms.
404
+ let one_tbps = Bandwidth::from_mbits_per_second(1_000_000);
405
+ assert_eq!(
406
+ one_tbps.to_bytes_per_period(Duration::from_millis(10)),
407
+ 1_250_000_000
408
+ );
409
+ }
410
+
411
+ #[test]
412
+ fn to_bytes_per_period_overflow_intermediate() {
413
+ // Test case that would overflow u64 in intermediate calculation:
414
+ // bits_per_second=10^19, time_period=1sec would give 10^19 * 10^9 =
415
+ // 10^28.
416
+ let huge_bw = Bandwidth {
417
+ bits_per_second: 10_000_000_000_000_000_000,
418
+ };
419
+ let result = huge_bw.to_bytes_per_period(Duration::from_secs(1));
420
+ assert_eq!(result, 1_250_000_000_000_000_000);
421
+ }
422
+
423
+ #[test]
424
+ fn to_bytes_per_period_saturate_very_high_bandwidth() {
425
+ // Test case where result exceeds u64::MAX and should saturate.
426
+ // 2^63 bits/sec * 100 seconds / 8 = 6.25 * u64::MAX bytes.
427
+ let very_high_bw = Bandwidth {
428
+ bits_per_second: 1u64 << 63, // 2^63
429
+ };
430
+ let result = very_high_bw.to_bytes_per_period(Duration::from_secs(100));
431
+ // Should saturate to u64::MAX since result exceeds u64 range.
432
+ assert_eq!(result, u64::MAX);
433
+ }
434
+
435
+ #[test]
436
+ fn to_bytes_per_period_saturate_long_period() {
437
+ // Test saturation case: high bandwidth, long period.
438
+ let high_bw = Bandwidth {
439
+ bits_per_second: u64::MAX / 2,
440
+ };
441
+ let result = high_bw.to_bytes_per_period(Duration::from_secs(100));
442
+ // Should saturate to u64::MAX.
443
+ assert_eq!(result, u64::MAX);
444
+ }
445
+
446
+ #[test]
447
+ fn to_bytes_per_period_large_no_saturate() {
448
+ // Test large but reasonable case that doesn't saturate.
449
+ let high_bw = Bandwidth::from_mbits_per_second(100_000); // 100 Gbps
450
+ let one_hour = Duration::from_secs(3600);
451
+ let result = high_bw.to_bytes_per_period(one_hour);
452
+ assert_eq!(result, 45_000_000_000_000); // 45 TB
453
+ }
454
+
455
+ #[test]
456
+ fn to_bytes_per_period_infinite() {
457
+ // Infinite bandwidth sentinel should return u64::MAX.
458
+ let inf = Bandwidth::infinite();
459
+ assert_eq!(inf.to_bytes_per_period(Duration::from_secs(1)), u64::MAX);
460
+ assert_eq!(inf.to_bytes_per_period(Duration::from_millis(1)), u64::MAX);
461
+ assert_eq!(inf.to_bytes_per_period(Duration::ZERO), 0);
462
+
463
+ // Mul<Duration> should also return u64::MAX.
464
+ assert_eq!(inf * Duration::from_secs(1), u64::MAX);
465
+ }
466
+
467
+ #[test]
468
+ fn to_bytes_per_period_duration_exceeds_u64_nanos() {
469
+ // Test case where duration.as_nanos() exceeds u64::MAX.
470
+ // u64::MAX nanoseconds is ~584 years. We can create a Duration larger
471
+ // than that. Duration::MAX is ~584 billion years.
472
+ let bw = Bandwidth::from_mbits_per_second(1000); // 1 Gbps
473
+
474
+ // Create a duration that exceeds u64::MAX nanoseconds.
475
+ // u64::MAX = 18_446_744_073_709_551_615 nanoseconds
476
+ // = 18_446_744_073 seconds + 709_551_615 nanoseconds
477
+ // So any duration > 18_446_744_073 seconds will exceed u64::MAX nanos.
478
+ let huge_duration = Duration::from_secs(20_000_000_000); // ~634 years
479
+
480
+ // Should fall back to u128 arithmetic and not panic.
481
+ // 1 Gbps * 20 billion seconds = 2.5 * 10^18 bytes
482
+ let result = bw.to_bytes_per_period(huge_duration);
483
+ assert_eq!(result, 2_500_000_000_000_000_000);
484
+ }
485
+
486
+ #[test]
487
+ fn to_bytes_per_period_u128_overflow() {
488
+ // Test case where even u128 multiplication would overflow.
489
+ // u128::MAX is ~3.4 * 10^38. Duration::MAX.as_nanos() is ~10^29.
490
+ // We need bits_per_second * time_nanos > u128::MAX.
491
+ // Use maximum possible values: u64::MAX - 1 bits/sec (since u64::MAX
492
+ // is infinite sentinel) and Duration::MAX.
493
+ let huge_bw = Bandwidth {
494
+ bits_per_second: u64::MAX - 1,
495
+ };
496
+ let max_duration = Duration::MAX;
497
+
498
+ // u128 multiplication should overflow and saturate to u64::MAX.
499
+ // (u64::MAX - 1) * Duration::MAX.as_nanos() > u128::MAX
500
+ let result = huge_bw.to_bytes_per_period(max_duration);
501
+ assert_eq!(result, u64::MAX);
502
+ }
503
+
504
+ #[test]
505
+ fn debug() {
506
+ assert_eq!(
507
+ format!("{:?}", Bandwidth { bits_per_second: 1 }),
508
+ "0.00 Kbps"
509
+ );
510
+ assert_eq!(
511
+ format!("{:?}", Bandwidth {
512
+ bits_per_second: 12
513
+ }),
514
+ "0.01 Kbps"
515
+ );
516
+ assert_eq!(
517
+ format!("{:?}", Bandwidth {
518
+ bits_per_second: 123
519
+ }),
520
+ "0.12 Kbps"
521
+ );
522
+ assert_eq!(
523
+ format!("{:?}", Bandwidth {
524
+ bits_per_second: 1234
525
+ }),
526
+ "1.23 Kbps"
527
+ );
528
+ assert_eq!(
529
+ format!("{:?}", Bandwidth {
530
+ bits_per_second: 12345
531
+ }),
532
+ "12.35 Kbps"
533
+ );
534
+ assert_eq!(
535
+ format!("{:?}", Bandwidth {
536
+ bits_per_second: 123456
537
+ }),
538
+ "123.46 Kbps"
539
+ );
540
+ assert_eq!(
541
+ format!("{:?}", Bandwidth {
542
+ bits_per_second: 1234567
543
+ }),
544
+ "1.23 Mbps"
545
+ );
546
+ assert_eq!(
547
+ format!("{:?}", Bandwidth {
548
+ bits_per_second: 12345678
549
+ }),
550
+ "12.35 Mbps"
551
+ );
552
+ assert_eq!(
553
+ format!("{:?}", Bandwidth {
554
+ bits_per_second: 123456789
555
+ }),
556
+ "123.46 Mbps"
557
+ );
558
+ assert_eq!(
559
+ format!("{:?}", Bandwidth {
560
+ bits_per_second: 1234567890
561
+ }),
562
+ "1.23 Gbps"
563
+ );
564
+ }
565
+ }