diff --git a/Cargo.toml b/Cargo.toml index da532f7199..8deffe25a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,10 @@ resolver = "2" homepage = "https://github.com/mozilla/neqo/" repository = "https://github.com/mozilla/neqo/" authors = ["The Neqo Authors "] +description = "Neqo, the Mozilla implementation of QUIC in Rust." +keywords = ["quic", "http3", "neqo", "mozilla", "ietf", "firefox"] +categories = ["network-programming", "web-programming"] +readme = "README.md" version = "0.7.9" # Keep in sync with `.rustfmt.toml` `edition`. edition = "2021" @@ -30,7 +34,10 @@ log = { version = "0.4", default-features = false } qlog = { version = "0.13", default-features = false } [workspace.lints.clippy] +cargo = { level = "warn", priority = -1 } +nursery = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 } +multiple_crate_versions = "allow" [profile.release] lto = "fat" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 6fd0941867..3e2a11e426 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [package.metadata] cargo-fuzz = true diff --git a/fuzz/fuzz_targets/frame.rs b/fuzz/fuzz_targets/frame.rs index 56f733a783..bfdc94f302 100644 --- a/fuzz/fuzz_targets/frame.rs +++ b/fuzz/fuzz_targets/frame.rs @@ -10,7 +10,7 @@ fuzz_target!(|data: &[u8]| { // Run the fuzzer let mut decoder = Decoder::new(data); - let _ = Frame::decode(&mut decoder); + _ = Frame::decode(&mut decoder); }); #[cfg(any(not(fuzzing), windows))] diff --git a/fuzz/fuzz_targets/packet.rs b/fuzz/fuzz_targets/packet.rs index 3080a75e70..91a9af4223 100644 --- a/fuzz/fuzz_targets/packet.rs +++ b/fuzz/fuzz_targets/packet.rs @@ -14,7 +14,7 @@ fuzz_target!(|data: &[u8]| { neqo_crypto::init().unwrap(); // Run the fuzzer - let _ = PublicPacket::decode(data, decoder); + _ = PublicPacket::decode(data, decoder); }); #[cfg(any(not(fuzzing), windows))] diff --git a/neqo-bin/Cargo.toml b/neqo-bin/Cargo.toml index adcaa496cb..9e336f4fed 100644 --- a/neqo-bin/Cargo.toml +++ b/neqo-bin/Cargo.toml @@ -8,6 +8,9 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [[bin]] name = "neqo-client" diff --git a/neqo-bin/benches/main.rs b/neqo-bin/benches/main.rs index 8ccff22fd0..b0daa48ddb 100644 --- a/neqo-bin/benches/main.rs +++ b/neqo-bin/benches/main.rs @@ -68,6 +68,7 @@ fn transfer(c: &mut Criterion) { done_sender.send(()).unwrap(); } +#[allow(clippy::redundant_pub_crate)] // Bug in clippy nursery? Not sure how this lint could fire here. fn spawn_server() -> tokio::sync::oneshot::Sender<()> { let (done_sender, mut done_receiver) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { @@ -76,7 +77,7 @@ fn spawn_server() -> tokio::sync::oneshot::Sender<()> { tokio::select! { _ = &mut done_receiver => {} res = &mut server => panic!("expect server not to terminate: {res:?}"), - } + }; }); }); done_sender diff --git a/neqo-bin/src/client/http09.rs b/neqo-bin/src/client/http09.rs index 964e09c822..ba251322b9 100644 --- a/neqo-bin/src/client/http09.rs +++ b/neqo-bin/src/client/http09.rs @@ -106,7 +106,7 @@ impl<'a> super::Handler for Handler<'a> { } } -pub(crate) fn create_client( +pub fn create_client( args: &Args, local_addr: SocketAddr, remote_addr: SocketAddr, @@ -147,11 +147,9 @@ impl TryFrom<&State> for CloseState { fn try_from(value: &State) -> Result { let (state, error) = match value { - State::Closing { error, .. } | State::Draining { error, .. } => { - (CloseState::Closing, error) - } - State::Closed(error) => (CloseState::Closed, error), - _ => return Ok(CloseState::NotClosing), + State::Closing { error, .. } | State::Draining { error, .. } => (Self::Closing, error), + State::Closed(error) => (Self::Closed, error), + _ => return Ok(Self::NotClosing), }; if error.is_error() { diff --git a/neqo-bin/src/client/http3.rs b/neqo-bin/src/client/http3.rs index 8284bd5d34..5b2c799abe 100644 --- a/neqo-bin/src/client/http3.rs +++ b/neqo-bin/src/client/http3.rs @@ -29,7 +29,7 @@ use url::Url; use super::{get_output_file, qlog_new, Args, CloseState, Res}; -pub(crate) struct Handler<'a> { +pub struct Handler<'a> { #[allow( unknown_lints, clippy::struct_field_names, @@ -62,7 +62,7 @@ impl<'a> Handler<'a> { } } -pub(crate) fn create_client( +pub fn create_client( args: &Args, local_addr: SocketAddr, remote_addr: SocketAddr, @@ -110,13 +110,13 @@ impl TryFrom for CloseState { fn try_from(value: Http3State) -> Result { let (state, error) = match value { - Http3State::Closing(error) => (CloseState::Closing, error), - Http3State::Closed(error) => (CloseState::Closed, error), - _ => return Ok(CloseState::NotClosing), + Http3State::Closing(error) => (Self::Closing, error), + Http3State::Closed(error) => (Self::Closed, error), + _ => return Ok(Self::NotClosing), }; if error.is_error() { - Err(error.clone()) + Err(error) } else { Ok(state) } @@ -452,7 +452,7 @@ impl<'a> UrlHandler<'a> { } } - fn done(&mut self) -> bool { + fn done(&self) -> bool { self.stream_handlers.is_empty() && self.url_queue.is_empty() } diff --git a/neqo-bin/src/client/mod.rs b/neqo-bin/src/client/mod.rs index 1fc213d281..b146834702 100644 --- a/neqo-bin/src/client/mod.rs +++ b/neqo-bin/src/client/mod.rs @@ -4,6 +4,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(clippy::future_not_send)] + use std::{ collections::{HashMap, VecDeque}, fmt::{self, Display}, @@ -332,7 +334,7 @@ async fn ready( let socket_ready = Box::pin(socket.readable()).map_ok(|()| Ready::Socket); let timeout_ready = timeout .as_mut() - .map_or(Either::Right(futures::future::pending()), Either::Left) + .map_or_else(|| Either::Right(futures::future::pending()), Either::Left) .map(|()| Ok(Ready::Timeout)); select(socket_ready, timeout_ready).await.factor_first().0 } diff --git a/neqo-bin/src/server/http09.rs b/neqo-bin/src/server/http09.rs index efc0bf49fb..d570f3661a 100644 --- a/neqo-bin/src/server/http09.rs +++ b/neqo-bin/src/server/http09.rs @@ -75,12 +75,7 @@ impl HttpServer { }) } - fn save_partial( - &mut self, - stream_id: StreamId, - partial: Vec, - conn: &mut ActiveConnectionRef, - ) { + fn save_partial(&mut self, stream_id: StreamId, partial: Vec, conn: &ActiveConnectionRef) { let url_dbg = String::from_utf8(partial.clone()) .unwrap_or_else(|_| format!("", hex(&partial))); if partial.len() < 4096 { @@ -92,12 +87,7 @@ impl HttpServer { } } - fn write( - &mut self, - stream_id: StreamId, - data: Option>, - conn: &mut ActiveConnectionRef, - ) { + fn write(&mut self, stream_id: StreamId, data: Option>, conn: &ActiveConnectionRef) { let resp = data.unwrap_or_else(|| Vec::from(&b"404 That request was nonsense\r\n"[..])); if let Some(stream_state) = self.write_state.get_mut(&stream_id) { match stream_state.data_to_send { @@ -120,7 +110,7 @@ impl HttpServer { } } - fn stream_readable(&mut self, stream_id: StreamId, conn: &mut ActiveConnectionRef) { + fn stream_readable(&mut self, stream_id: StreamId, conn: &ActiveConnectionRef) { if !stream_id.is_client_initiated() || !stream_id.is_bidi() { qdebug!("Stream {} not client-initiated bidi, ignoring", stream_id); return; @@ -176,7 +166,7 @@ impl HttpServer { self.write(stream_id, resp, conn); } - fn stream_writable(&mut self, stream_id: StreamId, conn: &mut ActiveConnectionRef) { + fn stream_writable(&mut self, stream_id: StreamId, conn: &ActiveConnectionRef) { match self.write_state.get_mut(&stream_id) { None => { qwarn!("Unknown stream {stream_id}, ignoring event"); @@ -209,8 +199,11 @@ impl super::HttpServer for HttpServer { } fn process_events(&mut self, now: Instant) { + // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable + // types. + #[allow(clippy::mutable_key_type)] let active_conns = self.server.active_connections(); - for mut acr in active_conns { + for acr in active_conns { loop { let event = match acr.borrow_mut().next_event() { None => break, @@ -222,10 +215,10 @@ impl super::HttpServer for HttpServer { .insert(stream_id, HttpStreamState::default()); } ConnectionEvent::RecvStreamReadable { stream_id } => { - self.stream_readable(stream_id, &mut acr); + self.stream_readable(stream_id, &acr); } ConnectionEvent::SendStreamWritable { stream_id } => { - self.stream_writable(stream_id, &mut acr); + self.stream_writable(stream_id, &acr); } ConnectionEvent::StateChange(State::Connected) => { acr.connection() diff --git a/neqo-bin/src/server/http3.rs b/neqo-bin/src/server/http3.rs index 56f4407a44..0a77a5ffa5 100644 --- a/neqo-bin/src/server/http3.rs +++ b/neqo-bin/src/server/http3.rs @@ -91,7 +91,7 @@ impl super::HttpServer for HttpServer { while let Some(event) = self.server.next_event() { match event { Http3ServerEvent::Headers { - mut stream, + stream, headers, fin, } => { @@ -138,17 +138,17 @@ impl super::HttpServer for HttpServer { Header::new("content-length", response.remaining.to_string()), ]) .unwrap(); - response.send(&mut stream); + response.send(&stream); if response.done() { stream.stream_close_send().unwrap(); } else { self.remaining_data.insert(stream.stream_id(), response); } } - Http3ServerEvent::DataWritable { mut stream } => { + Http3ServerEvent::DataWritable { stream } => { if self.posts.get_mut(&stream).is_none() { if let Some(remaining) = self.remaining_data.get_mut(&stream.stream_id()) { - remaining.send(&mut stream); + remaining.send(&stream); if remaining.done() { self.remaining_data.remove(&stream.stream_id()); stream.stream_close_send().unwrap(); @@ -157,11 +157,7 @@ impl super::HttpServer for HttpServer { } } - Http3ServerEvent::Data { - mut stream, - data, - fin, - } => { + Http3ServerEvent::Data { stream, data, fin } => { if let Some(received) = self.posts.get_mut(&stream) { *received += data.len(); } @@ -210,7 +206,7 @@ impl From> for ResponseData { } impl ResponseData { - fn repeat(buf: &'static [u8], total: usize) -> Self { + const fn repeat(buf: &'static [u8], total: usize) -> Self { Self { data: Cow::Borrowed(buf), offset: 0, @@ -218,7 +214,7 @@ impl ResponseData { } } - fn send(&mut self, stream: &mut Http3OrWebTransportStream) { + fn send(&mut self, stream: &Http3OrWebTransportStream) { while self.remaining > 0 { let end = min(self.data.len(), self.offset + self.remaining); let slice = &self.data[self.offset..end]; @@ -238,7 +234,7 @@ impl ResponseData { } } - fn done(&self) -> bool { + const fn done(&self) -> bool { self.remaining == 0 } } diff --git a/neqo-bin/src/server/mod.rs b/neqo-bin/src/server/mod.rs index caa6f23a95..0f58d8b928 100644 --- a/neqo-bin/src/server/mod.rs +++ b/neqo-bin/src/server/mod.rs @@ -4,6 +4,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(clippy::future_not_send)] + use std::{ cell::RefCell, fmt::{self, Display}, @@ -261,7 +263,7 @@ impl ServerRunner { let timeout_ready = self .timeout .as_mut() - .map_or(Either::Right(futures::future::pending()), Either::Left) + .map_or_else(|| Either::Right(futures::future::pending()), Either::Left) .map(|()| Ok(Ready::Timeout)); select(sockets_ready, timeout_ready).await.factor_first().0 } diff --git a/neqo-common/Cargo.toml b/neqo-common/Cargo.toml index bce2eab2b7..dec3f41bdc 100644 --- a/neqo-common/Cargo.toml +++ b/neqo-common/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/neqo-common/src/codec.rs b/neqo-common/src/codec.rs index 7fea2f71ab..018286c0f7 100644 --- a/neqo-common/src/codec.rs +++ b/neqo-common/src/codec.rs @@ -17,19 +17,19 @@ pub struct Decoder<'a> { impl<'a> Decoder<'a> { /// Make a new view of the provided slice. #[must_use] - pub fn new(buf: &[u8]) -> Decoder { + pub const fn new(buf: &[u8]) -> Decoder { Decoder { buf, offset: 0 } } /// Get the number of bytes remaining until the end. #[must_use] - pub fn remaining(&self) -> usize { + pub const fn remaining(&self) -> usize { self.buf.len() - self.offset } /// The number of bytes from the underlying slice that have been decoded. #[must_use] - pub fn offset(&self) -> usize { + pub const fn offset(&self) -> usize { self.offset } @@ -73,7 +73,8 @@ impl<'a> Decoder<'a> { } /// Provides the next byte without moving the read position. - pub fn peek_byte(&mut self) -> Option { + #[must_use] + pub const fn peek_byte(&self) -> Option { if self.remaining() < 1 { None } else { @@ -170,7 +171,7 @@ impl<'a> Debug for Decoder<'a> { impl<'a> From<&'a [u8]> for Decoder<'a> { #[must_use] - fn from(buf: &'a [u8]) -> Decoder<'a> { + fn from(buf: &'a [u8]) -> Self { Decoder::new(buf) } } @@ -180,7 +181,7 @@ where T: AsRef<[u8]>, { #[must_use] - fn from(buf: &'a T) -> Decoder<'a> { + fn from(buf: &'a T) -> Self { Decoder::new(buf.as_ref()) } } @@ -632,7 +633,7 @@ mod tests { #[test] #[should_panic(expected = "Varint value too large")] - fn encoded_length_oob() { + const fn encoded_length_oob() { _ = Encoder::varint_len(1 << 62); } diff --git a/neqo-common/src/datagram.rs b/neqo-common/src/datagram.rs index 1a5a63f9b5..b2d346d02a 100644 --- a/neqo-common/src/datagram.rs +++ b/neqo-common/src/datagram.rs @@ -27,17 +27,17 @@ impl Datagram { } #[must_use] - pub fn source(&self) -> SocketAddr { + pub const fn source(&self) -> SocketAddr { self.src } #[must_use] - pub fn destination(&self) -> SocketAddr { + pub const fn destination(&self) -> SocketAddr { self.dst } #[must_use] - pub fn tos(&self) -> IpTos { + pub const fn tos(&self) -> IpTos { self.tos } diff --git a/neqo-common/src/hrtime.rs b/neqo-common/src/hrtime.rs index e70b5f0ffb..c3c1419860 100644 --- a/neqo-common/src/hrtime.rs +++ b/neqo-common/src/hrtime.rs @@ -22,8 +22,8 @@ use winapi::um::timeapi::{timeBeginPeriod, timeEndPeriod}; struct Period(u8); impl Period { - const MAX: Period = Period(16); - const MIN: Period = Period(1); + const MAX: Self = Self(16); + const MIN: Self = Self(1); #[cfg(windows)] fn as_uint(self) -> UINT { @@ -63,8 +63,9 @@ impl PeriodSet { fn remove(&mut self, p: Period) { if p != Period::MAX { - debug_assert_ne!(*self.idx(p), 0); - *self.idx(p) -= 1; + let p = self.idx(p); + debug_assert_ne!(*p, 0); + *p -= 1; } } @@ -219,7 +220,7 @@ pub struct Handle { impl Handle { const HISTORY: usize = 8; - fn new(hrt: Rc>, active: Period) -> Self { + const fn new(hrt: Rc>, active: Period) -> Self { Self { hrt, active, @@ -287,6 +288,7 @@ impl Time { } #[allow(clippy::unused_self)] // Only on some platforms is it unused. + #[allow(clippy::missing_const_for_fn)] // Only const on some platforms where the function is empty. fn start(&self) { #[cfg(target_os = "macos")] { @@ -306,6 +308,7 @@ impl Time { } #[allow(clippy::unused_self)] // Only on some platforms is it unused. + #[allow(clippy::missing_const_for_fn)] // Only const on some platforms where the function is empty. fn stop(&self) { #[cfg(windows)] { @@ -344,7 +347,7 @@ impl Time { HR_TIME.with(|r| { let mut b = r.borrow_mut(); let hrt = b.upgrade().unwrap_or_else(|| { - let hrt = Rc::new(RefCell::new(Time::new())); + let hrt = Rc::new(RefCell::new(Self::new())); *b = Rc::downgrade(&hrt); hrt }); diff --git a/neqo-common/src/incrdecoder.rs b/neqo-common/src/incrdecoder.rs index 8468102cb6..43a135f497 100644 --- a/neqo-common/src/incrdecoder.rs +++ b/neqo-common/src/incrdecoder.rs @@ -39,19 +39,21 @@ impl IncrementalDecoderUint { None } } else { - let (v, remaining) = match dv.decode_byte() { - Some(b) => ( - u64::from(b & 0x3f), - match b >> 6 { - 0 => 0, - 1 => 1, - 2 => 3, - 3 => 7, - _ => unreachable!(), - }, - ), - None => unreachable!(), - }; + let (v, remaining) = dv.decode_byte().map_or_else( + || unreachable!(), + |b| { + ( + u64::from(b & 0x3f), + match b >> 6 { + 0 => 0, + 1 => 1, + 2 => 3, + 3 => 7, + _ => unreachable!(), + }, + ) + }, + ); self.remaining = Some(remaining); self.v = v; if remaining == 0 { @@ -63,7 +65,7 @@ impl IncrementalDecoderUint { } #[must_use] - pub fn decoding_in_progress(&self) -> bool { + pub const fn decoding_in_progress(&self) -> bool { self.remaining.is_some() } } @@ -76,7 +78,7 @@ pub struct IncrementalDecoderBuffer { impl IncrementalDecoderBuffer { #[must_use] - pub fn new(n: usize) -> Self { + pub const fn new(n: usize) -> Self { Self { v: Vec::new(), remaining: n, @@ -84,7 +86,7 @@ impl IncrementalDecoderBuffer { } #[must_use] - pub fn min_remaining(&self) -> usize { + pub const fn min_remaining(&self) -> usize { self.remaining } @@ -124,7 +126,7 @@ impl IncrementalDecoderIgnore { } #[must_use] - pub fn min_remaining(&self) -> usize { + pub const fn min_remaining(&self) -> usize { self.remaining } diff --git a/neqo-common/src/lib.rs b/neqo-common/src/lib.rs index 3f2b5f17fa..5b212f9998 100644 --- a/neqo-common/src/lib.rs +++ b/neqo-common/src/lib.rs @@ -90,7 +90,7 @@ pub enum Role { impl Role { #[must_use] - pub fn remote(self) -> Self { + pub const fn remote(self) -> Self { match self { Self::Client => Self::Server, Self::Server => Self::Client, diff --git a/neqo-common/src/qlog.rs b/neqo-common/src/qlog.rs index c67ce62afe..c0a4cbc960 100644 --- a/neqo-common/src/qlog.rs +++ b/neqo-common/src/qlog.rs @@ -60,7 +60,7 @@ impl NeqoQlog { } /// If logging enabled, closure may generate an event to be logged. - pub fn add_event(&mut self, f: F) + pub fn add_event(&self, f: F) where F: FnOnce() -> Option, { @@ -73,7 +73,7 @@ impl NeqoQlog { } /// If logging enabled, closure may generate an event to be logged. - pub fn add_event_data(&mut self, f: F) + pub fn add_event_data(&self, f: F) where F: FnOnce() -> Option, { @@ -87,7 +87,7 @@ impl NeqoQlog { /// If logging enabled, closure is given the Qlog stream to write events and /// frames to. - pub fn add_event_with_stream(&mut self, f: F) + pub fn add_event_with_stream(&self, f: F) where F: FnOnce(&mut QlogStreamer) -> Result<(), qlog::Error>, { @@ -174,7 +174,7 @@ mod test { #[test] fn add_event() { - let (mut log, contents) = test_fixture::new_neqo_qlog(); + let (log, contents) = test_fixture::new_neqo_qlog(); log.add_event(|| Some(Event::with_time(1.1, EV_DATA))); assert_eq!( contents.to_string(), diff --git a/neqo-common/src/tos.rs b/neqo-common/src/tos.rs index c7e5228dee..9661d82ecf 100644 --- a/neqo-common/src/tos.rs +++ b/neqo-common/src/tos.rs @@ -30,17 +30,17 @@ pub enum IpTosEcn { impl From for u8 { fn from(v: IpTosEcn) -> Self { - v as u8 + v as Self } } impl From for IpTosEcn { fn from(v: u8) -> Self { match v & 0b0000_0011 { - 0b00 => IpTosEcn::NotEct, - 0b01 => IpTosEcn::Ect1, - 0b10 => IpTosEcn::Ect0, - 0b11 => IpTosEcn::Ce, + 0b00 => Self::NotEct, + 0b01 => Self::Ect1, + 0b10 => Self::Ect0, + 0b11 => Self::Ce, _ => unreachable!(), } } @@ -48,16 +48,16 @@ impl From for IpTosEcn { impl From for IpTosEcn { fn from(v: IpTos) -> Self { - IpTosEcn::from(u8::from(v)) + Self::from(u8::from(v)) } } impl IpTosEcn { #[must_use] - pub fn is_ecn_marked(&self) -> bool { + pub const fn is_ecn_marked(&self) -> bool { match self { - IpTosEcn::Ect0 | IpTosEcn::Ect1 | IpTosEcn::Ce => true, - IpTosEcn::NotEct => false, + Self::Ect0 | Self::Ect1 | Self::Ce => true, + Self::NotEct => false, } } } @@ -140,36 +140,36 @@ pub enum IpTosDscp { impl From for u8 { fn from(v: IpTosDscp) -> Self { - v as u8 + v as Self } } impl From for IpTosDscp { fn from(v: u8) -> Self { match v & 0b1111_1100 { - 0b0000_0000 => IpTosDscp::Cs0, - 0b0010_0000 => IpTosDscp::Cs1, - 0b0100_0000 => IpTosDscp::Cs2, - 0b0110_0000 => IpTosDscp::Cs3, - 0b1000_0000 => IpTosDscp::Cs4, - 0b1010_0000 => IpTosDscp::Cs5, - 0b1100_0000 => IpTosDscp::Cs6, - 0b1110_0000 => IpTosDscp::Cs7, - 0b0010_1000 => IpTosDscp::Af11, - 0b0011_0000 => IpTosDscp::Af12, - 0b0011_1000 => IpTosDscp::Af13, - 0b0100_1000 => IpTosDscp::Af21, - 0b0101_0000 => IpTosDscp::Af22, - 0b0101_1000 => IpTosDscp::Af23, - 0b0110_1000 => IpTosDscp::Af31, - 0b0111_0000 => IpTosDscp::Af32, - 0b0111_1000 => IpTosDscp::Af33, - 0b1000_1000 => IpTosDscp::Af41, - 0b1001_0000 => IpTosDscp::Af42, - 0b1001_1000 => IpTosDscp::Af43, - 0b1011_1000 => IpTosDscp::Ef, - 0b1011_0000 => IpTosDscp::VoiceAdmit, - 0b0000_0100 => IpTosDscp::Le, + 0b0000_0000 => Self::Cs0, + 0b0010_0000 => Self::Cs1, + 0b0100_0000 => Self::Cs2, + 0b0110_0000 => Self::Cs3, + 0b1000_0000 => Self::Cs4, + 0b1010_0000 => Self::Cs5, + 0b1100_0000 => Self::Cs6, + 0b1110_0000 => Self::Cs7, + 0b0010_1000 => Self::Af11, + 0b0011_0000 => Self::Af12, + 0b0011_1000 => Self::Af13, + 0b0100_1000 => Self::Af21, + 0b0101_0000 => Self::Af22, + 0b0101_1000 => Self::Af23, + 0b0110_1000 => Self::Af31, + 0b0111_0000 => Self::Af32, + 0b0111_1000 => Self::Af33, + 0b1000_1000 => Self::Af41, + 0b1001_0000 => Self::Af42, + 0b1001_1000 => Self::Af43, + 0b1011_1000 => Self::Ef, + 0b1011_0000 => Self::VoiceAdmit, + 0b0000_0100 => Self::Le, _ => unreachable!(), } } @@ -177,7 +177,7 @@ impl From for IpTosDscp { impl From for IpTosDscp { fn from(v: IpTos) -> Self { - IpTosDscp::from(u8::from(v)) + Self::from(u8::from(v)) } } diff --git a/neqo-crypto/Cargo.toml b/neqo-crypto/Cargo.toml index b16c098fab..fc19872e8c 100644 --- a/neqo-crypto/Cargo.toml +++ b/neqo-crypto/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/neqo-crypto/build.rs b/neqo-crypto/build.rs index 5080f89d03..5e8ac6fda9 100644 --- a/neqo-crypto/build.rs +++ b/neqo-crypto/build.rs @@ -103,10 +103,10 @@ fn get_bash() -> PathBuf { // When running under MOZILLABUILD, we need to make sure not to invoke // another instance of bash that might be sitting around (like WSL). - match env::var("MOZILLABUILD") { - Ok(d) => PathBuf::from(d).join("msys").join("bin").join("bash.exe"), - Err(_) => PathBuf::from("bash"), - } + env::var("MOZILLABUILD").map_or_else( + |_| PathBuf::from("bash"), + |d| PathBuf::from(d).join("msys").join("bin").join("bash.exe"), + ) } fn build_nss(dir: PathBuf) { diff --git a/neqo-crypto/src/aead.rs b/neqo-crypto/src/aead.rs index 21027d55b2..36cf119dca 100644 --- a/neqo-crypto/src/aead.rs +++ b/neqo-crypto/src/aead.rs @@ -70,7 +70,7 @@ impl RealAead { #[must_use] #[allow(clippy::unused_self)] - pub fn expansion(&self) -> usize { + pub const fn expansion(&self) -> usize { 16 } diff --git a/neqo-crypto/src/aead_null.rs b/neqo-crypto/src/aead_null.rs index 6fcb72871f..a74c89f35d 100644 --- a/neqo-crypto/src/aead_null.rs +++ b/neqo-crypto/src/aead_null.rs @@ -18,12 +18,17 @@ pub struct AeadNull {} impl AeadNull { #[allow(clippy::missing_errors_doc)] - pub fn new(_version: Version, _cipher: Cipher, _secret: &SymKey, _prefix: &str) -> Res { + pub const fn new( + _version: Version, + _cipher: Cipher, + _secret: &SymKey, + _prefix: &str, + ) -> Res { Ok(Self {}) } #[must_use] - pub fn expansion(&self) -> usize { + pub const fn expansion(&self) -> usize { AEAD_NULL_TAG.len() } diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index c04accd775..9098a04a2b 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -60,17 +60,17 @@ pub enum HandshakeState { impl HandshakeState { #[must_use] - pub fn is_connected(&self) -> bool { + pub const fn is_connected(&self) -> bool { matches!(self, Self::Complete(_)) } #[must_use] - pub fn is_final(&self) -> bool { + pub const fn is_final(&self) -> bool { matches!(self, Self::Complete(_) | Self::Failed(_)) } #[must_use] - pub fn authentication_needed(&self) -> bool { + pub const fn authentication_needed(&self) -> bool { matches!( self, Self::AuthenticationPending | Self::EchFallbackAuthenticationPending(_) @@ -154,7 +154,7 @@ impl SecretAgentPreInfo { ); #[must_use] - pub fn early_data(&self) -> bool { + pub const fn early_data(&self) -> bool { self.info.canSendEarlyData != 0 } @@ -168,7 +168,7 @@ impl SecretAgentPreInfo { /// Was ECH accepted. #[must_use] - pub fn ech_accepted(&self) -> Option { + pub const fn ech_accepted(&self) -> Option { if self.info.valuesSet & ssl::ssl_preinfo_ech == 0 { None } else { @@ -198,7 +198,7 @@ impl SecretAgentPreInfo { } #[must_use] - pub fn alpn(&self) -> Option<&String> { + pub const fn alpn(&self) -> Option<&String> { self.alpn.as_ref() } } @@ -238,35 +238,35 @@ impl SecretAgentInfo { }) } #[must_use] - pub fn version(&self) -> Version { + pub const fn version(&self) -> Version { self.version } #[must_use] - pub fn cipher_suite(&self) -> Cipher { + pub const fn cipher_suite(&self) -> Cipher { self.cipher } #[must_use] - pub fn key_exchange(&self) -> Group { + pub const fn key_exchange(&self) -> Group { self.group } #[must_use] - pub fn resumed(&self) -> bool { + pub const fn resumed(&self) -> bool { self.resumed } #[must_use] - pub fn early_data_accepted(&self) -> bool { + pub const fn early_data_accepted(&self) -> bool { self.early_data } #[must_use] - pub fn ech_accepted(&self) -> bool { + pub const fn ech_accepted(&self) -> bool { self.ech_accepted } #[must_use] - pub fn alpn(&self) -> Option<&String> { + pub const fn alpn(&self) -> Option<&String> { self.alpn.as_ref() } #[must_use] - pub fn signature_scheme(&self) -> SignatureScheme { + pub const fn signature_scheme(&self) -> SignatureScheme { self.signature_scheme } } @@ -343,6 +343,7 @@ impl SecretAgent { Ok(fd) } + #[allow(clippy::missing_const_for_fn)] unsafe extern "C" fn auth_complete_hook( arg: *mut c_void, _fd: *mut ssl::PRFileDesc, @@ -482,7 +483,7 @@ impl SecretAgent { /// # Errors /// /// Returns an error if the option or option value is invalid; i.e., never. - pub fn set_option(&mut self, opt: ssl::Opt, value: bool) -> Res<()> { + pub fn set_option(&self, opt: ssl::Opt, value: bool) -> Res<()> { opt.set(self.fd, value) } @@ -491,7 +492,7 @@ impl SecretAgent { /// # Errors /// /// See `set_option`. - pub fn enable_0rtt(&mut self) -> Res<()> { + pub fn enable_0rtt(&self) -> Res<()> { self.set_option(ssl::Opt::EarlyData, true) } @@ -500,7 +501,7 @@ impl SecretAgent { /// # Errors /// /// See `set_option`. - pub fn disable_end_of_early_data(&mut self) -> Res<()> { + pub fn disable_end_of_early_data(&self) -> Res<()> { self.set_option(ssl::Opt::SuppressEndOfEarlyData, true) } @@ -597,7 +598,7 @@ impl SecretAgent { /// /// Calling this function returns None until the connection is complete. #[must_use] - pub fn info(&self) -> Option<&SecretAgentInfo> { + pub const fn info(&self) -> Option<&SecretAgentInfo> { match self.state { HandshakeState::Complete(ref info) => Some(info), _ => None, @@ -753,7 +754,7 @@ impl SecretAgent { if self.fd.is_null() { return; } - if let Some(true) = self.raw { + if self.raw == Some(true) { // Need to hold the record list in scope until the close is done. let _records = self.setup_raw().expect("Can only close"); unsafe { prio::PR_Close(self.fd.cast()) }; @@ -768,7 +769,7 @@ impl SecretAgent { /// State returns the status of the handshake. #[must_use] - pub fn state(&self) -> &HandshakeState { + pub const fn state(&self) -> &HandshakeState { &self.state } @@ -817,7 +818,7 @@ impl AsRef<[u8]> for ResumptionToken { impl ResumptionToken { #[must_use] - pub fn new(token: Vec, expiration_time: Instant) -> Self { + pub const fn new(token: Vec, expiration_time: Instant) -> Self { Self { token, expiration_time, @@ -825,7 +826,7 @@ impl ResumptionToken { } #[must_use] - pub fn expiration_time(&self) -> Instant { + pub const fn expiration_time(&self) -> Instant { self.expiration_time } } diff --git a/neqo-crypto/src/agentio.rs b/neqo-crypto/src/agentio.rs index 3beede5c12..bad9f58119 100644 --- a/neqo-crypto/src/agentio.rs +++ b/neqo-crypto/src/agentio.rs @@ -209,7 +209,7 @@ pub struct AgentIo { } impl AgentIo { - pub fn new() -> Self { + pub const fn new() -> Self { Self { input: AgentIoInput { input: null(), @@ -280,10 +280,9 @@ unsafe extern "C" fn agent_recv( return PR_FAILURE; } if let Ok(a) = usize::try_from(amount) { - match io.input.read_input(buf.cast(), a) { - Ok(v) => prio::PRInt32::try_from(v).unwrap_or(PR_FAILURE), - Err(_) => PR_FAILURE, - } + io.input.read_input(buf.cast(), a).map_or(PR_FAILURE, |v| { + prio::PRInt32::try_from(v).unwrap_or(PR_FAILURE) + }) } else { PR_FAILURE } @@ -295,12 +294,10 @@ unsafe extern "C" fn agent_write( amount: prio::PRInt32, ) -> PrStatus { let io = AgentIo::borrow(&mut fd); - if let Ok(a) = usize::try_from(amount) { + usize::try_from(amount).map_or(PR_FAILURE, |a| { io.save_output(buf.cast(), a); amount - } else { - PR_FAILURE - } + }) } unsafe extern "C" fn agent_send( @@ -315,12 +312,10 @@ unsafe extern "C" fn agent_send( if flags != 0 { return PR_FAILURE; } - if let Ok(a) = usize::try_from(amount) { + usize::try_from(amount).map_or(PR_FAILURE, |a| { io.save_output(buf.cast(), a); amount - } else { - PR_FAILURE - } + }) } unsafe extern "C" fn agent_available(mut fd: PrFd) -> prio::PRInt32 { diff --git a/neqo-crypto/src/cert.rs b/neqo-crypto/src/cert.rs index 2836b5237c..48afbd95f9 100644 --- a/neqo-crypto/src/cert.rs +++ b/neqo-crypto/src/cert.rs @@ -60,18 +60,14 @@ fn stapled_ocsp_responses(fd: *mut PRFileDesc) -> Option>> { fn signed_cert_timestamp(fd: *mut PRFileDesc) -> Option> { let sct_nss = unsafe { SSL_PeerSignedCertTimestamps(fd) }; - match NonNull::new(sct_nss as *mut SECItem) { - Some(sct_ptr) => { - if unsafe { sct_ptr.as_ref().len == 0 || sct_ptr.as_ref().data.is_null() } { - Some(Vec::new()) - } else { - let sct_slice = - unsafe { null_safe_slice(sct_ptr.as_ref().data, sct_ptr.as_ref().len) }; - Some(sct_slice.to_owned()) - } + NonNull::new(sct_nss as *mut SECItem).map(|sct_ptr| { + if unsafe { sct_ptr.as_ref().len == 0 || sct_ptr.as_ref().data.is_null() } { + Vec::new() + } else { + let sct_slice = unsafe { null_safe_slice(sct_ptr.as_ref().data, sct_ptr.as_ref().len) }; + sct_slice.to_owned() } - None => None, - } + }) } impl CertificateInfo { @@ -106,11 +102,13 @@ impl<'a> Iterator for &'a mut CertificateInfo { } impl CertificateInfo { - pub fn stapled_ocsp_responses(&mut self) -> &Option>> { + #[must_use] + pub const fn stapled_ocsp_responses(&self) -> &Option>> { &self.stapled_ocsp_responses } - pub fn signed_cert_timestamp(&mut self) -> &Option> { + #[must_use] + pub const fn signed_cert_timestamp(&self) -> &Option> { &self.signed_cert_timestamp } } diff --git a/neqo-crypto/src/err.rs b/neqo-crypto/src/err.rs index 8d4f239a0b..897bf9718a 100644 --- a/neqo-crypto/src/err.rs +++ b/neqo-crypto/src/err.rs @@ -151,7 +151,7 @@ pub fn secstatus_to_res(rv: SECStatus) -> Res<()> { } } -pub fn is_blocked(result: &Res<()>) -> bool { +pub const fn is_blocked(result: &Res<()>) -> bool { match result { Err(Error::NssError { code, .. }) => *code == nspr::PR_WOULD_BLOCK_ERROR, _ => false, diff --git a/neqo-crypto/src/exp.rs b/neqo-crypto/src/exp.rs index 75867d80bb..c783439128 100644 --- a/neqo-crypto/src/exp.rs +++ b/neqo-crypto/src/exp.rs @@ -9,7 +9,9 @@ macro_rules! experimental_api { ( $n:ident ( $( $a:ident : $t:ty ),* $(,)? ) ) => { #[allow(non_snake_case)] #[allow(clippy::too_many_arguments)] - pub(crate) unsafe fn $n ( $( $a : $t ),* ) -> Result<(), $crate::err::Error> { + #[allow(clippy::missing_safety_doc)] + #[allow(clippy::missing_errors_doc)] + pub unsafe fn $n ( $( $a : $t ),* ) -> Result<(), $crate::err::Error> { const EXP_FUNCTION: &str = stringify!($n); let n = ::std::ffi::CString::new(EXP_FUNCTION)?; let f = $crate::ssl::SSL_GetExperimentalAPI(n.as_ptr()); diff --git a/neqo-crypto/src/hkdf.rs b/neqo-crypto/src/hkdf.rs index 3706be6c3b..2bdf40a4ff 100644 --- a/neqo-crypto/src/hkdf.rs +++ b/neqo-crypto/src/hkdf.rs @@ -103,10 +103,7 @@ pub fn extract( ikm: &SymKey, ) -> Res { let mut prk: *mut PK11SymKey = null_mut(); - let salt_ptr: *mut PK11SymKey = match salt { - Some(s) => **s, - None => null_mut(), - }; + let salt_ptr: *mut PK11SymKey = salt.map_or(null_mut(), |s| **s); unsafe { SSL_HkdfExtract(version, cipher, salt_ptr, **ikm, &mut prk) }?; SymKey::from_ptr(prk) } diff --git a/neqo-crypto/src/hp.rs b/neqo-crypto/src/hp.rs index 1eba6a9cb5..8544b76b93 100644 --- a/neqo-crypto/src/hp.rs +++ b/neqo-crypto/src/hp.rs @@ -127,11 +127,11 @@ impl HpKey { /// Get the sample size, which is also the output size. #[must_use] #[allow(clippy::unused_self)] // To maintain an API contract. - pub fn sample_size(&self) -> usize { + pub const fn sample_size(&self) -> usize { Self::SAMPLE_SIZE } - fn block_size(&self) -> usize { + const fn block_size(&self) -> usize { match self { Self::Aes(_) => 16, Self::Chacha(_) => 64, diff --git a/neqo-crypto/src/min_version.rs b/neqo-crypto/src/min_version.rs index 4386371b1b..edf58d8f38 100644 --- a/neqo-crypto/src/min_version.rs +++ b/neqo-crypto/src/min_version.rs @@ -6,4 +6,4 @@ /// The minimum version of NSS that is required by this version of neqo. /// Note that the string may contain whitespace at the beginning and/or end. -pub(crate) const MINIMUM_NSS_VERSION: &str = include_str!("../min_version.txt"); +pub const MINIMUM_NSS_VERSION: &str = include_str!("../min_version.txt"); diff --git a/neqo-crypto/src/p11.rs b/neqo-crypto/src/p11.rs index c235bb869c..4d2e91d952 100644 --- a/neqo-crypto/src/p11.rs +++ b/neqo-crypto/src/p11.rs @@ -187,7 +187,7 @@ scoped_ptr!(Slot, PK11SlotInfo, PK11_FreeSlot); impl Slot { pub fn internal() -> Res { let p = unsafe { PK11_GetInternalSlot() }; - Slot::from_ptr(p) + Self::from_ptr(p) } } @@ -267,7 +267,7 @@ impl Item { } /// Make an empty `SECItem` for passing as a mutable `SECItem*` argument. - pub fn make_empty() -> SECItem { + pub const fn make_empty() -> SECItem { SECItem { type_: SECItemType::siBuffer, data: null_mut(), @@ -328,8 +328,8 @@ impl RandomCache { const SIZE: usize = 256; const CUTOFF: usize = 32; - fn new() -> Self { - RandomCache { + const fn new() -> Self { + Self { cache: [0; Self::SIZE], used: Self::SIZE, } @@ -361,7 +361,7 @@ impl RandomCache { /// When `size` is too large or NSS fails. #[must_use] pub fn random() -> [u8; N] { - thread_local!(static CACHE: RefCell = RefCell::new(RandomCache::new())); + thread_local!(static CACHE: RefCell = const { RefCell::new(RandomCache::new()) }); let buf = [0; N]; if N <= RandomCache::CUTOFF { diff --git a/neqo-crypto/src/selfencrypt.rs b/neqo-crypto/src/selfencrypt.rs index d0a85830b0..1618a971a9 100644 --- a/neqo-crypto/src/selfencrypt.rs +++ b/neqo-crypto/src/selfencrypt.rs @@ -108,7 +108,7 @@ impl SelfEncrypt { Ok(output) } - fn select_key(&self, kid: u8) -> Option<&SymKey> { + const fn select_key(&self, kid: u8) -> Option<&SymKey> { if kid == self.key_id { Some(&self.key) } else { diff --git a/neqo-crypto/src/ssl.rs b/neqo-crypto/src/ssl.rs index 8aaacffae6..3cb3e90d74 100644 --- a/neqo-crypto/src/ssl.rs +++ b/neqo-crypto/src/ssl.rs @@ -56,7 +56,8 @@ pub enum Opt { impl Opt { // Cast is safe here because SSLOptions are within the i32 range #[allow(clippy::cast_possible_wrap)] - pub(crate) fn as_int(self) -> PRInt32 { + #[must_use] + pub const fn as_int(self) -> PRInt32 { let i = match self { Self::Locking => SSLOption::SSL_NO_LOCKS, Self::Tickets => SSLOption::SSL_ENABLE_SESSION_TICKETS, diff --git a/neqo-crypto/src/time.rs b/neqo-crypto/src/time.rs index 359436a854..837ed3ac4b 100644 --- a/neqo-crypto/src/time.rs +++ b/neqo-crypto/src/time.rs @@ -74,7 +74,7 @@ fn get_base() -> &'static TimeZero { }) } -pub(crate) fn init() { +pub fn init() { _ = get_base(); } @@ -123,21 +123,20 @@ impl TryInto for Time { fn try_into(self) -> Res { let base = get_base(); - if let Some(delta) = self.t.checked_duration_since(base.instant) { - if let Ok(d) = PRTime::try_from(delta.as_micros()) { - d.checked_add(base.prtime).ok_or(Error::TimeTravelError) - } else { - Err(Error::TimeTravelError) - } - } else { - // Try to go backwards from the base time. - let backwards = base.instant - self.t; // infallible - if let Ok(d) = PRTime::try_from(backwards.as_micros()) { - base.prtime.checked_sub(d).ok_or(Error::TimeTravelError) - } else { - Err(Error::TimeTravelError) - } - } + self.t.checked_duration_since(base.instant).map_or_else( + || { + // Try to go backwards from the base time. + let backwards = base.instant - self.t; // infallible + PRTime::try_from(backwards.as_micros()).map_or(Err(Error::TimeTravelError), |d| { + base.prtime.checked_sub(d).ok_or(Error::TimeTravelError) + }) + }, + |delta| { + PRTime::try_from(delta.as_micros()).map_or(Err(Error::TimeTravelError), |d| { + d.checked_add(base.prtime).ok_or(Error::TimeTravelError) + }) + }, + ) } } @@ -207,7 +206,7 @@ impl TimeHolder { impl Default for TimeHolder { fn default() -> Self { - TimeHolder { t: Box::pin(0) } + Self { t: Box::pin(0) } } } diff --git a/neqo-crypto/tests/ext.rs b/neqo-crypto/tests/ext.rs index c8732dd014..f66167b58c 100644 --- a/neqo-crypto/tests/ext.rs +++ b/neqo-crypto/tests/ext.rs @@ -43,8 +43,7 @@ struct SimpleExtensionHandler { } impl SimpleExtensionHandler { - #[allow(dead_code)] - pub fn negotiated(&self) -> bool { + pub const fn negotiated(&self) -> bool { self.written && self.handled } } diff --git a/neqo-crypto/tests/handshake.rs b/neqo-crypto/tests/handshake.rs index 3cb31337fd..717d347a1b 100644 --- a/neqo-crypto/tests/handshake.rs +++ b/neqo-crypto/tests/handshake.rs @@ -113,12 +113,8 @@ impl ZeroRttChecker for PermissiveZeroRttChecker { } } -fn zero_rtt_setup( - mode: Resumption, - client: &mut Client, - server: &mut Server, -) -> Option { - if let Resumption::WithZeroRtt = mode { +fn zero_rtt_setup(mode: Resumption, client: &Client, server: &mut Server) -> Option { + if matches!(mode, Resumption::WithZeroRtt) { client.enable_0rtt().expect("should enable 0-RTT on client"); let anti_replay = anti_replay(); @@ -141,7 +137,7 @@ pub fn resumption_setup(mode: Resumption) -> (Option, ResumptionToke let mut client = Client::new("server.example", true).expect("should create client"); let mut server = Server::new(&["key"]).expect("should create server"); - let anti_replay = zero_rtt_setup(mode, &mut client, &mut server); + let anti_replay = zero_rtt_setup(mode, &client, &mut server); connect(&mut client, &mut server); diff --git a/neqo-http3/Cargo.toml b/neqo-http3/Cargo.toml index 1edc590329..bc9e3225ee 100644 --- a/neqo-http3/Cargo.toml +++ b/neqo-http3/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/neqo-http3/src/buffered_send_stream.rs b/neqo-http3/src/buffered_send_stream.rs index 60da0512b5..c4a0a3087b 100644 --- a/neqo-http3/src/buffered_send_stream.rs +++ b/neqo-http3/src/buffered_send_stream.rs @@ -29,7 +29,7 @@ impl ::std::fmt::Display for BufferedStream { impl BufferedStream { #[must_use] - pub fn new(stream_id: StreamId) -> Self { + pub const fn new(stream_id: StreamId) -> Self { Self::Initialized { stream_id, buf: Vec::new(), @@ -113,7 +113,7 @@ impl BufferedStream { } impl From<&BufferedStream> for Option { - fn from(stream: &BufferedStream) -> Option { + fn from(stream: &BufferedStream) -> Self { if let BufferedStream::Initialized { stream_id, .. } = stream { Some(*stream_id) } else { diff --git a/neqo-http3/src/conn_params.rs b/neqo-http3/src/conn_params.rs index 23a5d2cc67..2417823156 100644 --- a/neqo-http3/src/conn_params.rs +++ b/neqo-http3/src/conn_params.rs @@ -43,7 +43,7 @@ impl Default for Http3Parameters { impl Http3Parameters { #[must_use] - pub fn get_connection_parameters(&self) -> &ConnectionParameters { + pub const fn get_connection_parameters(&self) -> &ConnectionParameters { &self.conn_params } @@ -65,7 +65,7 @@ impl Http3Parameters { } #[must_use] - pub fn get_max_table_size_encoder(&self) -> u64 { + pub const fn get_max_table_size_encoder(&self) -> u64 { self.qpack_settings.max_table_size_encoder } @@ -81,56 +81,56 @@ impl Http3Parameters { } #[must_use] - pub fn get_max_table_size_decoder(&self) -> u64 { + pub const fn get_max_table_size_decoder(&self) -> u64 { self.qpack_settings.max_table_size_decoder } #[must_use] - pub fn max_blocked_streams(mut self, max_blocked: u16) -> Self { + pub const fn max_blocked_streams(mut self, max_blocked: u16) -> Self { self.qpack_settings.max_blocked_streams = max_blocked; self } #[must_use] - pub fn get_max_blocked_streams(&self) -> u16 { + pub const fn get_max_blocked_streams(&self) -> u16 { self.qpack_settings.max_blocked_streams } #[must_use] - pub fn get_qpack_settings(&self) -> &QpackSettings { + pub const fn get_qpack_settings(&self) -> &QpackSettings { &self.qpack_settings } #[must_use] - pub fn max_concurrent_push_streams(mut self, max_push_streams: u64) -> Self { + pub const fn max_concurrent_push_streams(mut self, max_push_streams: u64) -> Self { self.max_concurrent_push_streams = max_push_streams; self } #[must_use] - pub fn get_max_concurrent_push_streams(&self) -> u64 { + pub const fn get_max_concurrent_push_streams(&self) -> u64 { self.max_concurrent_push_streams } #[must_use] - pub fn webtransport(mut self, webtransport: bool) -> Self { + pub const fn webtransport(mut self, webtransport: bool) -> Self { self.webtransport = webtransport; self } #[must_use] - pub fn get_webtransport(&self) -> bool { + pub const fn get_webtransport(&self) -> bool { self.webtransport } #[must_use] - pub fn http3_datagram(mut self, http3_datagram: bool) -> Self { + pub const fn http3_datagram(mut self, http3_datagram: bool) -> Self { self.http3_datagram = http3_datagram; self } #[must_use] - pub fn get_http3_datagram(&self) -> bool { + pub const fn get_http3_datagram(&self) -> bool { self.http3_datagram } } diff --git a/neqo-http3/src/connection.rs b/neqo-http3/src/connection.rs index d7a4563b97..acf2975d01 100644 --- a/neqo-http3/src/connection.rs +++ b/neqo-http3/src/connection.rs @@ -44,7 +44,7 @@ use crate::{ SendStreamEvents, }; -pub(crate) struct RequestDescription<'b, 't, T> +pub struct RequestDescription<'b, 't, T> where T: AsRequestTarget<'t> + ?Sized + Debug, { @@ -63,8 +63,8 @@ pub enum WebTransportSessionAcceptAction { impl ::std::fmt::Display for WebTransportSessionAcceptAction { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self { - WebTransportSessionAcceptAction::Accept => f.write_str("Accept"), - WebTransportSessionAcceptAction::Reject(_) => f.write_str("Reject"), + Self::Accept => f.write_str("Accept"), + Self::Reject(_) => f.write_str("Reject"), } } } @@ -101,11 +101,8 @@ pub enum Http3State { impl Http3State { #[must_use] - pub fn active(&self) -> bool { - matches!( - self, - Http3State::Connected | Http3State::GoingAway(_) | Http3State::ZeroRtt - ) + pub const fn active(&self) -> bool { + matches!(self, Self::Connected | Self::GoingAway(_) | Self::ZeroRtt) } } @@ -299,7 +296,7 @@ The call to function `receive` may produce `Http3ClientEvent::DataReadable`. Act data is done in the `read_data` function. */ #[derive(Debug)] -pub(crate) struct Http3Connection { +pub struct Http3Connection { role: Role, pub state: Http3State, local_params: Http3Parameters, @@ -376,7 +373,7 @@ impl Http3Connection { HttpZeroRttChecker::save(&self.local_params) } - fn create_qpack_streams(&mut self, conn: &mut Connection) -> Res<()> { + fn create_qpack_streams(&self, conn: &mut Connection) -> Res<()> { qdebug!([self], "create_qpack_streams."); self.qpack_encoder .borrow_mut() @@ -527,9 +524,9 @@ impl Http3Connection { self.handle_unblocked_streams(unblocked_streams, conn)?; Ok(ReceiveOutput::NoOutput) } - ReceiveOutput::ControlFrames(mut control_frames) => { + ReceiveOutput::ControlFrames(control_frames) => { let mut rest = Vec::new(); - for cf in control_frames.drain(..) { + for cf in control_frames { if let Some(not_handled) = self.handle_control_frame(cf)? { rest.push(not_handled); } @@ -894,7 +891,7 @@ impl Http3Connection { where T: AsRequestTarget<'t> + ?Sized + Debug, { - let final_headers = Http3Connection::create_fetch_headers(request)?; + let final_headers = Self::create_fetch_headers(request)?; let stream_type = if request.connect_type.is_some() { Http3StreamType::ExtendedConnect @@ -1141,7 +1138,7 @@ impl Http3Connection { Box::new(extended_conn.clone()), ); - let final_headers = Http3Connection::create_fetch_headers(&RequestDescription { + let final_headers = Self::create_fetch_headers(&RequestDescription { method: "CONNECT", target, headers, @@ -1428,7 +1425,7 @@ impl Http3Connection { } } - fn set_qpack_settings(&mut self, settings: &HSettings) -> Res<()> { + fn set_qpack_settings(&self, settings: &HSettings) -> Res<()> { let mut qpe = self.qpack_encoder.borrow_mut(); qpe.set_max_capacity(settings.get(HSettingType::MaxTableCapacity))?; qpe.set_max_blocked_streams(settings.get(HSettingType::BlockedStreams))?; @@ -1537,14 +1534,12 @@ impl Http3Connection { } fn recv_stream_is_critical(&self, stream_id: StreamId) -> bool { - if let Some(r) = self.recv_streams.get(&stream_id) { + self.recv_streams.get(&stream_id).map_or(false, |r| { matches!( r.stream_type(), Http3StreamType::Control | Http3StreamType::Encoder | Http3StreamType::Decoder ) - } else { - false - } + }) } fn send_stream_is_critical(&self, stream_id: StreamId) -> bool { @@ -1633,7 +1628,7 @@ impl Http3Connection { stream } - pub fn webtransport_enabled(&self) -> bool { + pub const fn webtransport_enabled(&self) -> bool { self.webtransport.enabled() } } diff --git a/neqo-http3/src/connection_client.rs b/neqo-http3/src/connection_client.rs index 53aadd35e5..fdc74268b1 100644 --- a/neqo-http3/src/connection_client.rs +++ b/neqo-http3/src/connection_client.rs @@ -52,7 +52,7 @@ where } } -fn alpn_from_quic_version(version: Version) -> &'static str { +const fn alpn_from_quic_version(version: Version) -> &'static str { match version { Version::Version2 | Version::Version1 => "h3", Version::Draft29 => "h3-29", @@ -68,7 +68,7 @@ fn alpn_from_quic_version(version: Version) -> &'static str { /// [connection.rs](https://github.com/mozilla/neqo/blob/main/neqo-http3/src/connection.rs) which /// implements common behavior for the client-side and the server-side. `Http3Client` structure /// implements the public API and set of functions that differ between the client and the server. - +/// /// The API is used for: /// - create and close an endpoint: /// - [`Http3Client::new`] @@ -353,7 +353,7 @@ impl Http3Client { } #[must_use] - pub fn role(&self) -> Role { + pub const fn role(&self) -> Role { self.conn.role() } @@ -1262,7 +1262,7 @@ impl Http3Client { } #[must_use] - pub fn webtransport_enabled(&self) -> bool { + pub const fn webtransport_enabled(&self) -> bool { self.base_handler.webtransport_enabled() } } diff --git a/neqo-http3/src/connection_server.rs b/neqo-http3/src/connection_server.rs index cc887a26fc..59f2190eba 100644 --- a/neqo-http3/src/connection_server.rs +++ b/neqo-http3/src/connection_server.rs @@ -228,7 +228,7 @@ impl Http3ServerHandler { } /// Take the next available event. - pub(crate) fn next_event(&mut self) -> Option { + pub(crate) fn next_event(&self) -> Option { self.events.next_event() } diff --git a/neqo-http3/src/control_stream_local.rs b/neqo-http3/src/control_stream_local.rs index 2f336c63a4..92d12ef97f 100644 --- a/neqo-http3/src/control_stream_local.rs +++ b/neqo-http3/src/control_stream_local.rs @@ -15,7 +15,7 @@ pub const HTTP3_UNI_STREAM_TYPE_CONTROL: u64 = 0x0; /// The local control stream, responsible for encoding frames and sending them #[derive(Debug)] -pub(crate) struct ControlStreamLocal { +pub struct ControlStreamLocal { stream: BufferedStream, /// `stream_id`s of outstanding request streams outstanding_priority_update: VecDeque, diff --git a/neqo-http3/src/control_stream_remote.rs b/neqo-http3/src/control_stream_remote.rs index aef4b4c0a4..63a01de083 100644 --- a/neqo-http3/src/control_stream_remote.rs +++ b/neqo-http3/src/control_stream_remote.rs @@ -15,7 +15,7 @@ use crate::{ /// The remote control stream is responsible only for reading frames. The frames are handled by /// `Http3Connection`. #[derive(Debug)] -pub(crate) struct ControlStreamRemote { +pub struct ControlStreamRemote { stream_id: StreamId, frame_reader: FrameReader, } diff --git a/neqo-http3/src/features/extended_connect/mod.rs b/neqo-http3/src/features/extended_connect/mod.rs index 77655833f7..45a3797d00 100644 --- a/neqo-http3/src/features/extended_connect/mod.rs +++ b/neqo-http3/src/features/extended_connect/mod.rs @@ -30,12 +30,12 @@ pub enum SessionCloseReason { } impl From for SessionCloseReason { - fn from(close_type: CloseType) -> SessionCloseReason { + fn from(close_type: CloseType) -> Self { match close_type { CloseType::ResetApp(e) | CloseType::ResetRemote(e) | CloseType::LocalError(e) => { - SessionCloseReason::Error(e) + Self::Error(e) } - CloseType::Done => SessionCloseReason::Clean { + CloseType::Done => Self::Clean { error: 0, message: String::new(), }, @@ -70,13 +70,13 @@ pub(crate) enum ExtendedConnectType { impl ExtendedConnectType { #[must_use] #[allow(clippy::unused_self)] // This will change when we have more features using ExtendedConnectType. - pub fn string(&self) -> &str { + pub const fn string(&self) -> &str { "webtransport" } #[allow(clippy::unused_self)] // This will change when we have more features using ExtendedConnectType. #[must_use] - pub fn get_stream_type(self, session_id: StreamId) -> Http3StreamType { + pub const fn get_stream_type(self, session_id: StreamId) -> Http3StreamType { Http3StreamType::WebTransport(session_id) } } @@ -84,7 +84,7 @@ impl ExtendedConnectType { impl From for HSettingType { fn from(_type: ExtendedConnectType) -> Self { // This will change when we have more features using ExtendedConnectType. - HSettingType::EnableWebTransport + Self::EnableWebTransport } } @@ -110,7 +110,7 @@ impl ExtendedConnectFeature { } #[must_use] - pub fn enabled(&self) -> bool { + pub const fn enabled(&self) -> bool { self.feature_negotiation.enabled() } } diff --git a/neqo-http3/src/features/extended_connect/tests/webtransport/datagrams.rs b/neqo-http3/src/features/extended_connect/tests/webtransport/datagrams.rs index 27b7d2b2f2..b6223f84be 100644 --- a/neqo-http3/src/features/extended_connect/tests/webtransport/datagrams.rs +++ b/neqo-http3/src/features/extended_connect/tests/webtransport/datagrams.rs @@ -22,7 +22,7 @@ fn no_datagrams() { Http3Parameters::default().webtransport(true), Http3Parameters::default().webtransport(true), ); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); assert_eq!( wt_session.max_datagram_size(), @@ -47,7 +47,7 @@ fn no_datagrams() { wt.check_no_datagram_received_server(); } -fn do_datagram_test(wt: &mut WtTest, wt_session: &mut WebTransportRequest) { +fn do_datagram_test(wt: &mut WtTest, wt_session: &WebTransportRequest) { assert_eq!( wt_session.max_datagram_size(), Ok(DATAGRAM_SIZE @@ -70,8 +70,8 @@ fn do_datagram_test(wt: &mut WtTest, wt_session: &mut WebTransportRequest) { #[test] fn datagrams() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - do_datagram_test(&mut wt, &mut wt_session); + let wt_session = wt.create_wt_session(); + do_datagram_test(&mut wt, &wt_session); } #[test] @@ -80,7 +80,7 @@ fn datagrams_server_only() { Http3Parameters::default().webtransport(true), wt_default_parameters(), ); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); assert_eq!( wt_session.max_datagram_size(), @@ -109,7 +109,7 @@ fn datagrams_client_only() { wt_default_parameters(), Http3Parameters::default().webtransport(true), ); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); assert_eq!( wt_session.max_datagram_size(), @@ -136,9 +136,9 @@ fn datagrams_client_only() { fn datagrams_multiple_session() { let mut wt = WtTest::new(); - let mut wt_session1 = wt.create_wt_session(); - do_datagram_test(&mut wt, &mut wt_session1); + let wt_session1 = wt.create_wt_session(); + do_datagram_test(&mut wt, &wt_session1); - let mut wt_session_2 = wt.create_wt_session(); - do_datagram_test(&mut wt, &mut wt_session_2); + let wt_session_2 = wt.create_wt_session(); + do_datagram_test(&mut wt, &wt_session_2); } diff --git a/neqo-http3/src/features/extended_connect/tests/webtransport/mod.rs b/neqo-http3/src/features/extended_connect/tests/webtransport/mod.rs index 42b14fca11..75ec1c6909 100644 --- a/neqo-http3/src/features/extended_connect/tests/webtransport/mod.rs +++ b/neqo-http3/src/features/extended_connect/tests/webtransport/mod.rs @@ -144,7 +144,7 @@ impl WtTest { while let Some(event) = self.server.next_event() { match event { Http3ServerEvent::WebTransport(WebTransportServerEvent::NewSession { - mut session, + session, headers, }) => { assert!( @@ -243,7 +243,7 @@ impl WtTest { let mut event_found = false; while let Some(event) = self.client.next_event() { - event_found = WtTest::session_closed_client( + event_found = Self::session_closed_client( &event, wt_session_id, expected_reason, @@ -256,7 +256,7 @@ impl WtTest { assert!(event_found); } - pub fn cancel_session_server(&mut self, wt_session: &mut WebTransportRequest) { + pub fn cancel_session_server(&mut self, wt_session: &WebTransportRequest) { wt_session.cancel_fetch(Error::HttpNoError.code()).unwrap(); self.exchange_packets(); } @@ -279,12 +279,12 @@ impl WtTest { } pub fn check_session_closed_event_server( - &mut self, - wt_session: &mut WebTransportRequest, + &self, + wt_session: &WebTransportRequest, expected_reeason: &SessionCloseReason, ) { let event = self.server.next_event().unwrap(); - assert!(WtTest::session_closed_server( + assert!(Self::session_closed_server( &event, wt_session.stream_id(), expected_reeason @@ -444,13 +444,13 @@ impl WtTest { } fn create_wt_stream_server( - wt_server_session: &mut WebTransportRequest, + wt_server_session: &WebTransportRequest, stream_type: StreamType, ) -> Http3OrWebTransportStream { wt_server_session.create_stream(stream_type).unwrap() } - fn send_data_server(&mut self, wt_stream: &mut Http3OrWebTransportStream, data: &[u8]) { + fn send_data_server(&mut self, wt_stream: &Http3OrWebTransportStream, data: &[u8]) { assert_eq!(wt_stream.send_data(data).unwrap(), data.len()); self.exchange_packets(); } @@ -494,26 +494,26 @@ impl WtTest { wt_stream.unwrap() } - fn close_stream_sending_server(&mut self, wt_stream: &mut Http3OrWebTransportStream) { + fn close_stream_sending_server(&mut self, wt_stream: &Http3OrWebTransportStream) { wt_stream.stream_close_send().unwrap(); self.exchange_packets(); } - fn reset_stream_server(&mut self, wt_stream: &mut Http3OrWebTransportStream) { + fn reset_stream_server(&mut self, wt_stream: &Http3OrWebTransportStream) { wt_stream .stream_reset_send(Error::HttpNoError.code()) .unwrap(); self.exchange_packets(); } - fn stream_stop_sending_server(&mut self, wt_stream: &mut Http3OrWebTransportStream) { + fn stream_stop_sending_server(&mut self, wt_stream: &Http3OrWebTransportStream) { wt_stream .stream_stop_sending(Error::HttpNoError.code()) .unwrap(); self.exchange_packets(); } - fn receive_reset_server(&mut self, expected_stream_id: StreamId, expected_error: u64) { + fn receive_reset_server(&self, expected_stream_id: StreamId, expected_error: u64) { let stream_reset = |e| { matches!( e, @@ -526,7 +526,7 @@ impl WtTest { assert!(self.server.events().any(stream_reset)); } - fn receive_stop_sending_server(&mut self, expected_stream_id: StreamId, expected_error: u64) { + fn receive_stop_sending_server(&self, expected_stream_id: StreamId, expected_error: u64) { let stop_sending = |e| { matches!( e, @@ -540,7 +540,7 @@ impl WtTest { } fn check_events_after_closing_session_server( - &mut self, + &self, expected_reset_ids: &[StreamId], expected_error_stream_reset: Option, expected_stop_sending_ids: &[StreamId], @@ -589,11 +589,7 @@ impl WtTest { .unwrap(); } - pub fn session_close_frame_server( - wt_session: &mut WebTransportRequest, - error: u32, - message: &str, - ) { + pub fn session_close_frame_server(wt_session: &WebTransportRequest, error: u32, message: &str) { wt_session.close_session(error, message).unwrap(); } @@ -623,7 +619,7 @@ impl WtTest { } fn check_datagram_received_server( - &mut self, + &self, expected_session: &WebTransportRequest, expected_dgram: &[u8], ) { @@ -649,7 +645,7 @@ impl WtTest { assert!(!self.client.events().any(wt_datagram_event)); } - fn check_no_datagram_received_server(&mut self) { + fn check_no_datagram_received_server(&self) { let wt_datagram_event = |e| { matches!( e, diff --git a/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs b/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs index 9b54f1dc46..eb316efee5 100644 --- a/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs +++ b/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs @@ -116,12 +116,9 @@ fn zero_rtt( client_resumed && server_resumed ); - let mut early_data_accepted = true; // The only case we should not do 0-RTT is when webtransport was enabled // originally and is disabled afterwards. - if server_org && !server_resumed { - early_data_accepted = false; - } + let early_data_accepted = !server_org || server_resumed; assert_eq!( client.tls_info().unwrap().early_data_accepted(), early_data_accepted diff --git a/neqo-http3/src/features/extended_connect/tests/webtransport/sessions.rs b/neqo-http3/src/features/extended_connect/tests/webtransport/sessions.rs index 5f929d0e4b..31337ce039 100644 --- a/neqo-http3/src/features/extended_connect/tests/webtransport/sessions.rs +++ b/neqo-http3/src/features/extended_connect/tests/webtransport/sessions.rs @@ -46,11 +46,11 @@ fn wt_session_reject() { #[test] fn wt_session_close_client() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); wt.cancel_session_client(wt_session.stream_id()); wt.check_session_closed_event_server( - &mut wt_session, + &wt_session, &SessionCloseReason::Error(Error::HttpNoError.code()), ); } @@ -58,9 +58,9 @@ fn wt_session_close_client() { #[test] fn wt_session_close_server() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_session_closed_event_client( wt_session.stream_id(), &SessionCloseReason::Error(Error::HttpNoError.code()), @@ -71,7 +71,7 @@ fn wt_session_close_server() { #[test] fn wt_session_close_server_close_send() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); wt_session.stream_close_send().unwrap(); wt.exchange_packets(); @@ -88,7 +88,7 @@ fn wt_session_close_server_close_send() { #[test] fn wt_session_close_server_stop_sending() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); wt_session .stream_stop_sending(Error::HttpNoError.code()) @@ -104,7 +104,7 @@ fn wt_session_close_server_stop_sending() { #[test] fn wt_session_close_server_reset() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); wt_session .stream_reset_send(Error::HttpNoError.code()) @@ -146,7 +146,7 @@ fn wt_session_response_with_1xx() { } } - let mut wt_server_session = wt_server_session.unwrap(); + let wt_server_session = wt_server_session.unwrap(); // Send interim response. wt_server_session @@ -221,7 +221,7 @@ fn wt_session_respone_200_with_fin() { } } - let mut wt_server_session = wt_server_session.unwrap(); + let wt_server_session = wt_server_session.unwrap(); wt_server_session .response(&WebTransportSessionAcceptAction::Accept) .unwrap(); @@ -254,13 +254,13 @@ fn wt_session_close_frame_client() { const ERROR_NUM: u32 = 23; const ERROR_MESSAGE: &str = "Something went wrong"; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); wt.session_close_frame_client(wt_session.stream_id(), ERROR_NUM, ERROR_MESSAGE); wt.exchange_packets(); wt.check_session_closed_event_server( - &mut wt_session, + &wt_session, &SessionCloseReason::Clean { error: ERROR_NUM, message: ERROR_MESSAGE.to_string(), @@ -273,9 +273,9 @@ fn wt_session_close_frame_server() { const ERROR_NUM: u32 = 23; const ERROR_MESSAGE: &str = "Something went wrong"; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - WtTest::session_close_frame_server(&mut wt_session, ERROR_NUM, ERROR_MESSAGE); + WtTest::session_close_frame_server(&wt_session, ERROR_NUM, ERROR_MESSAGE); wt.exchange_packets(); wt.check_session_closed_event_client( @@ -295,7 +295,7 @@ fn wt_unknown_session_frame_client() { const ERROR_NUM: u32 = 23; const ERROR_MESSAGE: &str = "Something went wrong"; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); // Send an unknown frame. let mut enc = Encoder::with_capacity(UNKNOWN_FRAME_LEN + 4); @@ -307,8 +307,8 @@ fn wt_unknown_session_frame_client() { wt.exchange_packets(); // The session is still active - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); wt.receive_data_client(unidi_server.stream_id(), true, BUF, false); // Now close the session. @@ -341,7 +341,7 @@ fn wt_unknown_session_frame_client() { #[test] fn wt_close_session_frame_broken_client() { let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); // Send a incorrect CloseSession frame. let mut enc = Encoder::default(); @@ -363,7 +363,7 @@ fn wt_close_session_frame_broken_client() { &None, ); wt.check_session_closed_event_server( - &mut wt_session, + &wt_session, &SessionCloseReason::Error(Error::HttpGeneralProtocolStream.code()), ); @@ -372,7 +372,7 @@ fn wt_close_session_frame_broken_client() { assert_eq!(wt_session.state(), Http3State::Connected); } -fn receive_request(server: &mut Http3Server) -> Option { +fn receive_request(server: &Http3Server) -> Option { while let Some(event) = server.next_event() { if let Http3ServerEvent::Headers { stream, .. } = event { return Some(stream); @@ -394,7 +394,7 @@ fn wt_close_session_cannot_be_sent_at_once() { let server = default_http3_server(wt_default_parameters()); let mut wt = WtTest::new_with(client, server); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); // Fill the flow control window using an unrelated http stream. let req_id = wt @@ -409,7 +409,7 @@ fn wt_close_session_cannot_be_sent_at_once() { .unwrap(); assert_eq!(req_id, 4); wt.exchange_packets(); - let mut req = receive_request(&mut wt.server).unwrap(); + let req = receive_request(&wt.server).unwrap(); req.send_headers(&[ Header::new(":status", "200"), Header::new("content-length", BUF.len().to_string()), @@ -418,7 +418,7 @@ fn wt_close_session_cannot_be_sent_at_once() { req.send_data(BUF).unwrap(); // Now close the session. - WtTest::session_close_frame_server(&mut wt_session, ERROR_NUM, ERROR_MESSAGE); + WtTest::session_close_frame_server(&wt_session, ERROR_NUM, ERROR_MESSAGE); // server cannot create new streams. assert_eq!( wt_session.create_stream(StreamType::UniDi), diff --git a/neqo-http3/src/features/extended_connect/tests/webtransport/streams.rs b/neqo-http3/src/features/extended_connect/tests/webtransport/streams.rs index b898dbb31e..682b7589b0 100644 --- a/neqo-http3/src/features/extended_connect/tests/webtransport/streams.rs +++ b/neqo-http3/src/features/extended_connect/tests/webtransport/streams.rs @@ -53,8 +53,8 @@ fn wt_client_stream_bidi() { let wt_session = wt.create_wt_session(); let wt_client_stream = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::BiDi); wt.send_data_client(wt_client_stream, BUF_CLIENT); - let mut wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, false); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + let wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, false); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_client_stream, false, BUF_SERVER, false); let send_stats = wt.send_stream_stats(wt_client_stream).unwrap(); assert_eq!(send_stats.bytes_written(), BUF_CLIENT.len() as u64); @@ -71,9 +71,9 @@ fn wt_server_stream_uni() { const BUF_SERVER: &[u8] = &[2; 30]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, false); let send_stats = wt.send_stream_stats(wt_server_stream.stream_id()); assert_eq!(send_stats.unwrap_err(), Error::InvalidStreamId); @@ -89,9 +89,9 @@ fn wt_server_stream_bidi() { const BUF_SERVER: &[u8] = &[1; 20]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, false); wt.send_data_client(wt_server_stream.stream_id(), BUF_CLIENT); mem::drop(wt.receive_data_server(wt_server_stream.stream_id(), false, BUF_CLIENT, false)); @@ -129,10 +129,10 @@ fn wt_client_stream_bidi_close() { wt.send_data_client(wt_client_stream, BUF_CLIENT); wt.close_stream_sending_client(wt_client_stream); - let mut wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, true); + let wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, true); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); - wt.close_stream_sending_server(&mut wt_server_stream); + wt.send_data_server(&wt_server_stream, BUF_SERVER); + wt.close_stream_sending_server(&wt_server_stream); wt.receive_data_client(wt_client_stream, false, BUF_SERVER, true); } @@ -141,10 +141,10 @@ fn wt_server_stream_uni_closed() { const BUF_SERVER: &[u8] = &[2; 30]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); - wt.close_stream_sending_server(&mut wt_server_stream); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); + wt.close_stream_sending_server(&wt_server_stream); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, true); } @@ -154,10 +154,10 @@ fn wt_server_stream_bidi_close() { const BUF_SERVER: &[u8] = &[1; 20]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); - wt.close_stream_sending_server(&mut wt_server_stream); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); + wt.close_stream_sending_server(&wt_server_stream); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, true); wt.send_data_client(wt_server_stream.stream_id(), BUF_CLIENT); wt.close_stream_sending_client(wt_server_stream.stream_id()); @@ -182,11 +182,11 @@ fn wt_server_stream_uni_reset() { const BUF_SERVER: &[u8] = &[2; 30]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, false); - wt.reset_stream_server(&mut wt_server_stream); + wt.reset_stream_server(&wt_server_stream); wt.receive_reset_client(wt_server_stream.stream_id()); } @@ -199,12 +199,12 @@ fn wt_client_stream_bidi_reset() { let wt_client_stream = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::BiDi); wt.send_data_client(wt_client_stream, BUF_CLIENT); - let mut wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, false); + let wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, false); wt.reset_stream_client(wt_client_stream); wt.receive_reset_server(wt_server_stream.stream_id(), Error::HttpNoError.code()); - wt.reset_stream_server(&mut wt_server_stream); + wt.reset_stream_server(&wt_server_stream); wt.receive_reset_client(wt_client_stream); } @@ -213,15 +213,15 @@ fn wt_server_stream_bidi_reset() { const BUF_SERVER: &[u8] = &[1; 20]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, false); wt.reset_stream_client(wt_server_stream.stream_id()); wt.receive_reset_server(wt_server_stream.stream_id(), Error::HttpNoError.code()); - wt.reset_stream_server(&mut wt_server_stream); + wt.reset_stream_server(&wt_server_stream); wt.receive_reset_client(wt_server_stream.stream_id()); } @@ -233,8 +233,8 @@ fn wt_client_stream_uni_stop_sending() { let wt_session = wt.create_wt_session(); let wt_stream = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::UniDi); wt.send_data_client(wt_stream, BUF_CLIENT); - let mut wt_server_stream = wt.receive_data_server(wt_stream, true, BUF_CLIENT, false); - wt.stream_stop_sending_server(&mut wt_server_stream); + let wt_server_stream = wt.receive_data_server(wt_stream, true, BUF_CLIENT, false); + wt.stream_stop_sending_server(&wt_server_stream); wt.receive_stop_sending_client(wt_stream); } @@ -243,9 +243,9 @@ fn wt_server_stream_uni_stop_sending() { const BUF_SERVER: &[u8] = &[2; 30]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, false); wt.stream_stop_sending_client(wt_server_stream.stream_id()); wt.receive_stop_sending_server(wt_server_stream.stream_id(), Error::HttpNoError.code()); @@ -262,12 +262,12 @@ fn wt_client_stream_bidi_stop_sending() { wt.send_data_client(wt_client_stream, BUF_CLIENT); - let mut wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, false); + let wt_server_stream = wt.receive_data_server(wt_client_stream, true, BUF_CLIENT, false); wt.stream_stop_sending_client(wt_client_stream); wt.receive_stop_sending_server(wt_server_stream.stream_id(), Error::HttpNoError.code()); - wt.stream_stop_sending_server(&mut wt_server_stream); + wt.stream_stop_sending_server(&wt_server_stream); wt.receive_stop_sending_client(wt_server_stream.stream_id()); } @@ -276,14 +276,14 @@ fn wt_server_stream_bidi_stop_sending() { const BUF_SERVER: &[u8] = &[1; 20]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); - let mut wt_server_stream = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); + let wt_session = wt.create_wt_session(); + let wt_server_stream = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); - wt.send_data_server(&mut wt_server_stream, BUF_SERVER); + wt.send_data_server(&wt_server_stream, BUF_SERVER); wt.receive_data_client(wt_server_stream.stream_id(), true, BUF_SERVER, false); wt.stream_stop_sending_client(wt_server_stream.stream_id()); wt.receive_stop_sending_server(wt_server_stream.stream_id(), Error::HttpNoError.code()); - wt.stream_stop_sending_server(&mut wt_server_stream); + wt.stream_stop_sending_server(&wt_server_stream); wt.receive_stop_sending_client(wt_server_stream.stream_id()); } @@ -414,8 +414,8 @@ fn wt_client_session_close_4() { let unidi_from_client = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::UniDi); wt.send_data_client(unidi_from_client, BUF); - let mut unidi_from_client_s = wt.receive_data_server(unidi_from_client, true, BUF, false); - wt.stream_stop_sending_server(&mut unidi_from_client_s); + let unidi_from_client_s = wt.receive_data_server(unidi_from_client, true, BUF, false); + wt.stream_stop_sending_server(&unidi_from_client_s); wt.cancel_session_client(wt_session.stream_id()); @@ -474,10 +474,10 @@ fn wt_client_session_close_6() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut bidi_from_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut bidi_from_server, BUF); + let bidi_from_server = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&bidi_from_server, BUF); wt.receive_data_client(bidi_from_server.stream_id(), true, BUF, false); wt.cancel_session_client(wt_session.stream_id()); @@ -508,10 +508,10 @@ fn wt_client_session_close_7() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_from_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_from_server, BUF); + let unidi_from_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_from_server, BUF); wt.receive_data_client(unidi_from_server.stream_id(), true, BUF, false); wt.cancel_session_client(wt_session.stream_id()); @@ -542,11 +542,11 @@ fn wt_client_session_close_8() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); - wt.close_stream_sending_server(&mut unidi_server); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); + wt.close_stream_sending_server(&unidi_server); wt.receive_data_client(unidi_server.stream_id(), true, BUF, true); wt.cancel_session_client(wt_session.stream_id()); @@ -570,10 +570,10 @@ fn wt_client_session_close_9() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); wt.stream_stop_sending_client(unidi_server.stream_id()); wt.cancel_session_client(wt_session.stream_id()); @@ -597,11 +597,11 @@ fn wt_client_session_close_10() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); - wt.close_stream_sending_server(&mut unidi_server); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); + wt.close_stream_sending_server(&unidi_server); wt.cancel_session_client(wt_session.stream_id()); @@ -631,13 +631,13 @@ fn wt_client_session_close_11() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut bidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut bidi_server, BUF); - wt.close_stream_sending_server(&mut bidi_server); + let bidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&bidi_server, BUF); + wt.close_stream_sending_server(&bidi_server); wt.receive_data_client(bidi_server.stream_id(), true, BUF, true); - wt.stream_stop_sending_server(&mut bidi_server); + wt.stream_stop_sending_server(&bidi_server); wt.receive_stop_sending_client(bidi_server.stream_id()); wt.cancel_session_client(wt_session.stream_id()); @@ -661,12 +661,12 @@ fn wt_client_session_close_12() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut bidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut bidi_server, BUF); - wt.close_stream_sending_server(&mut bidi_server); - wt.stream_stop_sending_server(&mut bidi_server); + let bidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&bidi_server, BUF); + wt.close_stream_sending_server(&bidi_server); + wt.stream_stop_sending_server(&bidi_server); wt.cancel_session_client(wt_session.stream_id()); @@ -746,13 +746,13 @@ fn wt_client_session_server_close_1() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); let bidi_client = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::BiDi); wt.send_data_client(bidi_client, BUF); std::mem::drop(wt.receive_data_server(bidi_client, true, BUF, false)); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[bidi_client], @@ -780,13 +780,13 @@ fn wt_client_session_server_close_2() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); let unidi_client = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::UniDi); wt.send_data_client(unidi_client, BUF); std::mem::drop(wt.receive_data_server(unidi_client, true, BUF, false)); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[], @@ -814,15 +814,15 @@ fn wt_client_session_server_close_3() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); let unidi_client = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::UniDi); wt.send_data_client(unidi_client, BUF); - let mut unidi_client_s = wt.receive_data_server(unidi_client, true, BUF, false); - wt.stream_stop_sending_server(&mut unidi_client_s); + let unidi_client_s = wt.receive_data_server(unidi_client, true, BUF, false); + wt.stream_stop_sending_server(&unidi_client_s); wt.receive_stop_sending_client(unidi_client); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[], @@ -844,14 +844,14 @@ fn wt_client_session_server_close_4() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); let unidi_client = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::UniDi); wt.send_data_client(unidi_client, BUF); - let mut unidi_client_s = wt.receive_data_server(unidi_client, true, BUF, false); - wt.stream_stop_sending_server(&mut unidi_client_s); + let unidi_client_s = wt.receive_data_server(unidi_client, true, BUF, false); + wt.stream_stop_sending_server(&unidi_client_s); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[], @@ -873,13 +873,13 @@ fn wt_client_session_server_close_5() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut bidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut bidi_server, BUF); + let bidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&bidi_server, BUF); wt.receive_data_client(bidi_server.stream_id(), true, BUF, false); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[bidi_server.stream_id()], @@ -907,13 +907,13 @@ fn wt_client_session_server_close_6() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); wt.receive_data_client(unidi_server.stream_id(), true, BUF, false); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[unidi_server.stream_id()], @@ -940,14 +940,14 @@ fn wt_client_session_server_close_7() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); - wt.close_stream_sending_server(&mut unidi_server); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); + wt.close_stream_sending_server(&unidi_server); wt.receive_data_client(unidi_server.stream_id(), true, BUF, true); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); // Already close stream will not have a reset event. wt.check_events_after_closing_session_client( @@ -970,13 +970,13 @@ fn wt_client_session_server_close_8() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); - wt.close_stream_sending_server(&mut unidi_server); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); + wt.close_stream_sending_server(&unidi_server); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); // The stream was only closed on the server side therefore it is cancelled on the client side. wt.check_events_after_closing_session_client( @@ -999,16 +999,16 @@ fn wt_client_session_server_close_9() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut bidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut bidi_server, BUF); - wt.close_stream_sending_server(&mut bidi_server); + let bidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&bidi_server, BUF); + wt.close_stream_sending_server(&bidi_server); wt.receive_data_client(bidi_server.stream_id(), true, BUF, true); - wt.stream_stop_sending_server(&mut bidi_server); + wt.stream_stop_sending_server(&bidi_server); wt.receive_stop_sending_client(bidi_server.stream_id()); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); // Already close stream will not have a reset event. wt.check_events_after_closing_session_client( @@ -1031,14 +1031,14 @@ fn wt_client_session_server_close_10() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut bidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::BiDi); - wt.send_data_server(&mut bidi_server, BUF); - wt.close_stream_sending_server(&mut bidi_server); - wt.stream_stop_sending_server(&mut bidi_server); + let bidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::BiDi); + wt.send_data_server(&bidi_server, BUF); + wt.close_stream_sending_server(&bidi_server); + wt.stream_stop_sending_server(&bidi_server); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[bidi_server.stream_id()], @@ -1060,7 +1060,7 @@ fn wt_client_session_server_close_11() { const BUF: &[u8] = &[0; 10]; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); let bidi_client_1 = wt.create_wt_stream_client(wt_session.stream_id(), StreamType::BiDi); wt.send_data_client(bidi_client_1, BUF); @@ -1069,7 +1069,7 @@ fn wt_client_session_server_close_11() { wt.send_data_client(bidi_client_2, BUF); std::mem::drop(wt.receive_data_server(bidi_client_2, true, BUF, false)); - wt.cancel_session_server(&mut wt_session); + wt.cancel_session_server(&wt_session); wt.check_events_after_closing_session_client( &[bidi_client_1, bidi_client_2], @@ -1098,10 +1098,10 @@ fn wt_session_close_frame_and_streams_client() { const ERROR_NUM: u32 = 23; const ERROR_MESSAGE: &str = "Something went wrong"; let mut wt = WtTest::new(); - let mut wt_session = wt.create_wt_session(); + let wt_session = wt.create_wt_session(); - let mut unidi_server = WtTest::create_wt_stream_server(&mut wt_session, StreamType::UniDi); - wt.send_data_server(&mut unidi_server, BUF); + let unidi_server = WtTest::create_wt_stream_server(&wt_session, StreamType::UniDi); + wt.send_data_server(&unidi_server, BUF); wt.exchange_packets(); wt.session_close_frame_client(wt_session.stream_id(), ERROR_NUM, ERROR_MESSAGE); diff --git a/neqo-http3/src/features/extended_connect/webtransport_session.rs b/neqo-http3/src/features/extended_connect/webtransport_session.rs index fdf2a02617..4ef43d53a9 100644 --- a/neqo-http3/src/features/extended_connect/webtransport_session.rs +++ b/neqo-http3/src/features/extended_connect/webtransport_session.rs @@ -29,13 +29,13 @@ enum SessionState { } impl SessionState { - pub fn closing_state(&self) -> bool { + pub const fn closing_state(&self) -> bool { matches!(self, Self::FinPending | Self::Done) } } #[derive(Debug)] -pub(crate) struct WebTransportSession { +pub struct WebTransportSession { control_stream_recv: Box, control_stream_send: Box, stream_event_listener: Rc>, @@ -295,7 +295,7 @@ impl WebTransportSession { } pub fn add_stream(&mut self, stream_id: StreamId) { - if let SessionState::Active = self.state { + if self.state == SessionState::Active { if stream_id.is_bidi() { self.send_streams.insert(stream_id); self.recv_streams.insert(stream_id); @@ -324,7 +324,7 @@ impl WebTransportSession { } #[must_use] - pub fn is_active(&self) -> bool { + pub const fn is_active(&self) -> bool { matches!(self.state, SessionState::Active) } @@ -411,7 +411,7 @@ impl WebTransportSession { id: impl Into, ) -> Res<()> { qtrace!([self], "send_datagram state={:?}", self.state); - if let SessionState::Active = self.state { + if self.state == SessionState::Active { let mut dgram_data = Encoder::default(); dgram_data.encode_varint(self.session_id.as_u64() / 4); dgram_data.encode(buf); @@ -423,8 +423,8 @@ impl WebTransportSession { Ok(()) } - pub fn datagram(&mut self, datagram: Vec) { - if let SessionState::Active = self.state { + pub fn datagram(&self, datagram: Vec) { + if self.state == SessionState::Active { self.events.new_datagram(self.session_id, datagram); } } diff --git a/neqo-http3/src/features/extended_connect/webtransport_streams.rs b/neqo-http3/src/features/extended_connect/webtransport_streams.rs index cdc692b8d7..c068b5b788 100644 --- a/neqo-http3/src/features/extended_connect/webtransport_streams.rs +++ b/neqo-http3/src/features/extended_connect/webtransport_streams.rs @@ -19,7 +19,7 @@ pub const WEBTRANSPORT_UNI_STREAM: u64 = 0x54; pub const WEBTRANSPORT_STREAM: u64 = 0x41; #[derive(Debug)] -pub(crate) struct WebTransportRecvStream { +pub struct WebTransportRecvStream { stream_id: StreamId, events: Box, session: Rc>, @@ -115,7 +115,7 @@ enum WebTransportSenderStreamState { } #[derive(Debug)] -pub(crate) struct WebTransportSendStream { +pub struct WebTransportSendStream { stream_id: StreamId, state: WebTransportSenderStreamState, events: Box, diff --git a/neqo-http3/src/features/mod.rs b/neqo-http3/src/features/mod.rs index 34e21f50ac..c44ff8eacd 100644 --- a/neqo-http3/src/features/mod.rs +++ b/neqo-http3/src/features/mod.rs @@ -35,7 +35,7 @@ pub enum NegotiationState { impl NegotiationState { #[must_use] - pub fn new(enable: bool, feature_type: HSettingType) -> Self { + pub const fn new(enable: bool, feature_type: HSettingType) -> Self { if enable { Self::Negotiating { feature_type, @@ -81,12 +81,12 @@ impl NegotiationState { } #[must_use] - pub fn enabled(&self) -> bool { + pub const fn enabled(&self) -> bool { matches!(self, &Self::Negotiated) } #[must_use] - pub fn locally_enabled(&self) -> bool { + pub const fn locally_enabled(&self) -> bool { !matches!(self, &Self::Disabled) } } diff --git a/neqo-http3/src/frames/hframe.rs b/neqo-http3/src/frames/hframe.rs index e69f7b449e..594ddbcf20 100644 --- a/neqo-http3/src/frames/hframe.rs +++ b/neqo-http3/src/frames/hframe.rs @@ -12,7 +12,7 @@ use neqo_transport::StreamId; use crate::{frames::reader::FrameDecoder, settings::HSettings, Error, Priority, Res}; -pub(crate) type HFrameType = u64; +pub type HFrameType = u64; pub const H3_FRAME_TYPE_DATA: HFrameType = 0x0; pub const H3_FRAME_TYPE_HEADERS: HFrameType = 0x1; @@ -142,7 +142,7 @@ impl HFrame { } } -impl FrameDecoder for HFrame { +impl FrameDecoder for HFrame { fn frame_type_allowed(frame_type: u64) -> Res<()> { if H3_RESERVED_FRAME_TYPES.contains(&frame_type) { return Err(Error::HttpFrameUnexpected); @@ -150,17 +150,17 @@ impl FrameDecoder for HFrame { Ok(()) } - fn decode(frame_type: u64, frame_len: u64, data: Option<&[u8]>) -> Res> { + fn decode(frame_type: u64, frame_len: u64, data: Option<&[u8]>) -> Res> { if frame_type == H3_FRAME_TYPE_DATA { - Ok(Some(HFrame::Data { len: frame_len })) + Ok(Some(Self::Data { len: frame_len })) } else if let Some(payload) = data { let mut dec = Decoder::from(payload); Ok(match frame_type { H3_FRAME_TYPE_DATA => unreachable!("DATA frame has been handled already."), - H3_FRAME_TYPE_HEADERS => Some(HFrame::Headers { + H3_FRAME_TYPE_HEADERS => Some(Self::Headers { header_block: dec.decode_remainder().to_vec(), }), - H3_FRAME_TYPE_CANCEL_PUSH => Some(HFrame::CancelPush { + H3_FRAME_TYPE_CANCEL_PUSH => Some(Self::CancelPush { push_id: dec.decode_varint().ok_or(Error::HttpFrame)?, }), H3_FRAME_TYPE_SETTINGS => { @@ -172,16 +172,16 @@ impl FrameDecoder for HFrame { Error::HttpFrame } })?; - Some(HFrame::Settings { settings }) + Some(Self::Settings { settings }) } - H3_FRAME_TYPE_PUSH_PROMISE => Some(HFrame::PushPromise { + H3_FRAME_TYPE_PUSH_PROMISE => Some(Self::PushPromise { push_id: dec.decode_varint().ok_or(Error::HttpFrame)?, header_block: dec.decode_remainder().to_vec(), }), - H3_FRAME_TYPE_GOAWAY => Some(HFrame::Goaway { + H3_FRAME_TYPE_GOAWAY => Some(Self::Goaway { stream_id: StreamId::new(dec.decode_varint().ok_or(Error::HttpFrame)?), }), - H3_FRAME_TYPE_MAX_PUSH_ID => Some(HFrame::MaxPushId { + H3_FRAME_TYPE_MAX_PUSH_ID => Some(Self::MaxPushId { push_id: dec.decode_varint().ok_or(Error::HttpFrame)?, }), H3_FRAME_TYPE_PRIORITY_UPDATE_REQUEST | H3_FRAME_TYPE_PRIORITY_UPDATE_PUSH => { @@ -189,12 +189,12 @@ impl FrameDecoder for HFrame { let priority = dec.decode_remainder(); let priority = Priority::from_bytes(priority)?; if frame_type == H3_FRAME_TYPE_PRIORITY_UPDATE_REQUEST { - Some(HFrame::PriorityUpdateRequest { + Some(Self::PriorityUpdateRequest { element_id, priority, }) } else { - Some(HFrame::PriorityUpdatePush { + Some(Self::PriorityUpdatePush { element_id, priority, }) diff --git a/neqo-http3/src/frames/mod.rs b/neqo-http3/src/frames/mod.rs index 8b615fad01..426e9dbb7a 100644 --- a/neqo-http3/src/frames/mod.rs +++ b/neqo-http3/src/frames/mod.rs @@ -4,18 +4,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub(crate) mod hframe; -pub(crate) mod reader; -pub(crate) mod wtframe; +pub mod hframe; +pub mod reader; +pub mod wtframe; #[allow(unused_imports)] -pub(crate) use hframe::{ - HFrame, H3_FRAME_TYPE_HEADERS, H3_FRAME_TYPE_SETTINGS, H3_RESERVED_FRAME_TYPES, -}; -pub(crate) use reader::{ - FrameReader, StreamReaderConnectionWrapper, StreamReaderRecvStreamWrapper, -}; -pub(crate) use wtframe::WebTransportFrame; +pub use hframe::{HFrame, H3_FRAME_TYPE_HEADERS, H3_FRAME_TYPE_SETTINGS, H3_RESERVED_FRAME_TYPES}; +pub use reader::{FrameReader, StreamReaderConnectionWrapper, StreamReaderRecvStreamWrapper}; +pub use wtframe::WebTransportFrame; #[cfg(test)] mod tests; diff --git a/neqo-http3/src/frames/reader.rs b/neqo-http3/src/frames/reader.rs index 1a086683cf..ee3ef307b2 100644 --- a/neqo-http3/src/frames/reader.rs +++ b/neqo-http3/src/frames/reader.rs @@ -18,7 +18,7 @@ use crate::{Error, RecvStream, Res}; const MAX_READ_SIZE: usize = 4096; -pub(crate) trait FrameDecoder { +pub trait FrameDecoder { fn is_known_type(frame_type: u64) -> bool; /// # Errors /// @@ -33,7 +33,7 @@ pub(crate) trait FrameDecoder { fn decode(frame_type: u64, frame_len: u64, data: Option<&[u8]>) -> Res>; } -pub(crate) trait StreamReader { +pub trait StreamReader { /// # Errors /// /// An error may happen while reading a stream, e.g. early close, protocol error, etc. @@ -42,7 +42,7 @@ pub(crate) trait StreamReader { fn read_data(&mut self, buf: &mut [u8]) -> Res<(usize, bool)>; } -pub(crate) struct StreamReaderConnectionWrapper<'a> { +pub struct StreamReaderConnectionWrapper<'a> { conn: &'a mut Connection, stream_id: StreamId, } @@ -63,7 +63,7 @@ impl<'a> StreamReader for StreamReaderConnectionWrapper<'a> { } } -pub(crate) struct StreamReaderRecvStreamWrapper<'a> { +pub struct StreamReaderRecvStreamWrapper<'a> { recv_stream: &'a mut Box, conn: &'a mut Connection, } @@ -93,7 +93,7 @@ enum FrameReaderState { #[allow(clippy::module_name_repetitions)] #[derive(Debug)] -pub(crate) struct FrameReader { +pub struct FrameReader { state: FrameReaderState, frame_type: u64, frame_len: u64, @@ -144,7 +144,7 @@ impl FrameReader { } } - fn decoding_in_progress(&self) -> bool { + const fn decoding_in_progress(&self) -> bool { if let FrameReaderState::GetType { decoder } = &self.state { decoder.decoding_in_progress() } else { diff --git a/neqo-http3/src/frames/tests/mod.rs b/neqo-http3/src/frames/tests/mod.rs index 33eea5497a..d386e8b5ed 100644 --- a/neqo-http3/src/frames/tests/mod.rs +++ b/neqo-http3/src/frames/tests/mod.rs @@ -16,7 +16,7 @@ use crate::frames::{ }; #[allow(clippy::many_single_char_names)] -pub(crate) fn enc_dec>(d: &Encoder, st: &str, remaining: usize) -> T { +pub fn enc_dec>(d: &Encoder, st: &str, remaining: usize) -> T { // For data, headers and push_promise we do not read all bytes from the buffer let d2 = Encoder::from_hex(st); assert_eq!(d.as_ref(), &d2.as_ref()[..d.as_ref().len()]); diff --git a/neqo-http3/src/frames/tests/reader.rs b/neqo-http3/src/frames/tests/reader.rs index fed1477ba4..a9b71fc429 100644 --- a/neqo-http3/src/frames/tests/reader.rs +++ b/neqo-http3/src/frames/tests/reader.rs @@ -226,14 +226,14 @@ fn test_reading_frame + PartialEq + Debug>( let mut fr = FrameReaderTest::new(); fr.conn_s.stream_send(fr.stream_id, buf).unwrap(); - if let FrameReadingTestSend::DataWithFin = test_to_send { + if matches!(test_to_send, FrameReadingTestSend::DataWithFin) { fr.conn_s.stream_close_send(fr.stream_id).unwrap(); } let out = fr.conn_s.process(None, now()); mem::drop(fr.conn_c.process(out.as_dgram_ref(), now())); - if let FrameReadingTestSend::DataThenFin = test_to_send { + if matches!(test_to_send, FrameReadingTestSend::DataThenFin) { fr.conn_s.stream_close_send(fr.stream_id).unwrap(); let out = fr.conn_s.process(None, now()); mem::drop(fr.conn_c.process(out.as_dgram_ref(), now())); diff --git a/neqo-http3/src/frames/wtframe.rs b/neqo-http3/src/frames/wtframe.rs index 20e9b81936..f2e0b32b56 100644 --- a/neqo-http3/src/frames/wtframe.rs +++ b/neqo-http3/src/frames/wtframe.rs @@ -8,7 +8,7 @@ use neqo_common::{Decoder, Encoder}; use crate::{frames::reader::FrameDecoder, Error, Res}; -pub(crate) type WebTransportFrameType = u64; +pub type WebTransportFrameType = u64; const WT_FRAME_CLOSE_SESSION: WebTransportFrameType = 0x2843; const WT_FRAME_CLOSE_MAX_MESSAGE_SIZE: u64 = 1024; @@ -21,19 +21,15 @@ pub enum WebTransportFrame { impl WebTransportFrame { pub fn encode(&self, enc: &mut Encoder) { enc.encode_varint(WT_FRAME_CLOSE_SESSION); - let WebTransportFrame::CloseSession { error, message } = &self; + let Self::CloseSession { error, message } = &self; enc.encode_varint(4 + message.len() as u64); enc.encode_uint(4, *error); enc.encode(message.as_bytes()); } } -impl FrameDecoder for WebTransportFrame { - fn decode( - frame_type: u64, - frame_len: u64, - data: Option<&[u8]>, - ) -> Res> { +impl FrameDecoder for WebTransportFrame { + fn decode(frame_type: u64, frame_len: u64, data: Option<&[u8]>) -> Res> { if let Some(payload) = data { let mut dec = Decoder::from(payload); if frame_type == WT_FRAME_CLOSE_SESSION { @@ -45,7 +41,7 @@ impl FrameDecoder for WebTransportFrame { let Ok(message) = String::from_utf8(dec.decode_remainder().to_vec()) else { return Err(Error::HttpMessageError); }; - Ok(Some(WebTransportFrame::CloseSession { error, message })) + Ok(Some(Self::CloseSession { error, message })) } else { Ok(None) } diff --git a/neqo-http3/src/lib.rs b/neqo-http3/src/lib.rs index d23ebc6994..17d5900182 100644 --- a/neqo-http3/src/lib.rs +++ b/neqo-http3/src/lib.rs @@ -235,7 +235,7 @@ pub enum Error { impl Error { #[must_use] - pub fn code(&self) -> AppError { + pub const fn code(&self) -> AppError { match self { Self::HttpNoError => 0x100, Self::HttpGeneralProtocol | Self::HttpGeneralProtocolStream | Self::InvalidHeader => { @@ -263,7 +263,7 @@ impl Error { } #[must_use] - pub fn connection_error(&self) -> bool { + pub const fn connection_error(&self) -> bool { matches!( self, Self::HttpGeneralProtocol @@ -281,7 +281,7 @@ impl Error { } #[must_use] - pub fn stream_reset_error(&self) -> bool { + pub const fn stream_reset_error(&self) -> bool { matches!(self, Self::HttpGeneralProtocolStream | Self::InvalidHeader) } @@ -289,15 +289,15 @@ impl Error { /// /// On unexpected errors, in debug mode. #[must_use] - pub fn map_stream_send_errors(err: &Error) -> Self { + pub fn map_stream_send_errors(err: &Self) -> Self { match err { Self::TransportError( TransportError::InvalidStreamId | TransportError::FinalSizeError, - ) => Error::TransportStreamDoesNotExist, - Self::TransportError(TransportError::InvalidInput) => Error::InvalidInput, + ) => Self::TransportStreamDoesNotExist, + Self::TransportError(TransportError::InvalidInput) => Self::InvalidInput, _ => { debug_assert!(false, "Unexpected error"); - Error::TransportStreamDoesNotExist + Self::TransportStreamDoesNotExist } } } @@ -308,11 +308,11 @@ impl Error { #[must_use] pub fn map_stream_create_errors(err: &TransportError) -> Self { match err { - TransportError::ConnectionState => Error::Unavailable, - TransportError::StreamLimitError => Error::StreamLimitError, + TransportError::ConnectionState => Self::Unavailable, + TransportError::StreamLimitError => Self::StreamLimitError, _ => { debug_assert!(false, "Unexpected error"); - Error::TransportStreamDoesNotExist + Self::TransportStreamDoesNotExist } } } @@ -321,7 +321,7 @@ impl Error { /// /// On unexpected errors, in debug mode. #[must_use] - pub fn map_stream_recv_errors(err: &Error) -> Self { + pub fn map_stream_recv_errors(err: &Self) -> Self { match err { Self::TransportError(TransportError::NoMoreData) => { debug_assert!( @@ -334,14 +334,14 @@ impl Error { debug_assert!(false, "Unexpected error"); } }; - Error::TransportStreamDoesNotExist + Self::TransportStreamDoesNotExist } #[must_use] - pub fn map_set_resumption_errors(err: &TransportError) -> Self { + pub const fn map_set_resumption_errors(err: &TransportError) -> Self { match err { - TransportError::ConnectionState => Error::InvalidState, - _ => Error::InvalidResumptionToken, + TransportError::ConnectionState => Self::InvalidState, + _ => Self::InvalidResumptionToken, } } @@ -370,7 +370,7 @@ impl From for Error { impl From for Error { fn from(err: QpackError) -> Self { match err { - QpackError::ClosedCriticalStream => Error::HttpClosedCriticalStream, + QpackError::ClosedCriticalStream => Self::HttpClosedCriticalStream, e => Self::QpackError(e), } } @@ -513,7 +513,7 @@ pub struct Http3StreamInfo { impl Http3StreamInfo { #[must_use] - pub fn new(stream_id: StreamId, stream_type: Http3StreamType) -> Self { + pub const fn new(stream_id: StreamId, stream_type: Http3StreamType) -> Self { Self { stream_id, stream_type, @@ -521,12 +521,12 @@ impl Http3StreamInfo { } #[must_use] - pub fn stream_id(&self) -> StreamId { + pub const fn stream_id(&self) -> StreamId { self.stream_id } #[must_use] - pub fn session_id(&self) -> Option { + pub const fn session_id(&self) -> Option { if let Http3StreamType::WebTransport(session) = self.stream_type { Some(session) } else { @@ -640,7 +640,7 @@ enum CloseType { impl CloseType { #[must_use] - pub fn error(&self) -> Option { + pub const fn error(&self) -> Option { match self { Self::ResetApp(error) | Self::ResetRemote(error) | Self::LocalError(error) => { Some(*error) @@ -650,7 +650,7 @@ impl CloseType { } #[must_use] - pub fn locally_initiated(&self) -> bool { - matches!(self, CloseType::ResetApp(_)) + pub const fn locally_initiated(&self) -> bool { + matches!(self, Self::ResetApp(_)) } } diff --git a/neqo-http3/src/priority.rs b/neqo-http3/src/priority.rs index 76a2cb9a85..deca549277 100644 --- a/neqo-http3/src/priority.rs +++ b/neqo-http3/src/priority.rs @@ -19,7 +19,7 @@ pub struct Priority { impl Default for Priority { fn default() -> Self { - Priority { + Self { urgency: 3, incremental: false, } @@ -31,9 +31,9 @@ impl Priority { /// /// If an invalid urgency (>7 is given) #[must_use] - pub fn new(urgency: u8, incremental: bool) -> Priority { + pub fn new(urgency: u8, incremental: bool) -> Self { assert!(urgency < 8); - Priority { + Self { urgency, incremental, } @@ -43,7 +43,7 @@ impl Priority { #[must_use] pub fn header(self) -> Option
{ match self { - Priority { + Self { urgency: 3, incremental: false, } => None, @@ -60,7 +60,7 @@ impl Priority { /// # Panics /// /// Never, but the compiler is not smart enough to work that out. - pub fn from_bytes(bytes: &[u8]) -> Res { + pub fn from_bytes(bytes: &[u8]) -> Res { let dict = Parser::parse_dictionary(bytes).map_err(|_| Error::HttpFrame)?; let urgency = match dict.get("u") { Some(ListEntry::Item(Item { @@ -76,7 +76,7 @@ impl Priority { })) => *i, _ => false, }; - Ok(Priority { + Ok(Self { urgency, incremental, }) @@ -86,19 +86,19 @@ impl Priority { impl fmt::Display for Priority { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Priority { + Self { urgency: 3, incremental: false, } => Ok(()), - Priority { + Self { urgency: 3, incremental: true, } => write!(f, "i"), - Priority { + Self { urgency, incremental: false, } => write!(f, "u={urgency}"), - Priority { + Self { urgency, incremental: true, } => write!(f, "u={urgency},i"), @@ -115,8 +115,8 @@ pub struct PriorityHandler { } impl PriorityHandler { - pub fn new(push_stream: bool, priority: Priority) -> PriorityHandler { - PriorityHandler { + pub const fn new(push_stream: bool, priority: Priority) -> Self { + Self { push_stream, priority, last_send_priority: priority, diff --git a/neqo-http3/src/push_controller.rs b/neqo-http3/src/push_controller.rs index ab6afccdf6..7f22cba0f1 100644 --- a/neqo-http3/src/push_controller.rs +++ b/neqo-http3/src/push_controller.rs @@ -61,7 +61,7 @@ struct ActivePushStreams { } impl ActivePushStreams { - pub fn new() -> Self { + pub const fn new() -> Self { Self { push_streams: VecDeque::new(), first_push_id: 0, @@ -98,7 +98,7 @@ impl ActivePushStreams { None | Some(PushState::Closed) => None, Some(s) => { let res = mem::replace(s, PushState::Closed); - while let Some(PushState::Closed) = self.push_streams.front() { + while self.push_streams.front() == Some(&PushState::Closed) { self.push_streams.pop_front(); self.first_push_id += 1; } @@ -144,7 +144,7 @@ impl ActivePushStreams { /// `CANCEL_PUSH` frame. The difference is that `PushCanceled` will not /// be posted and a `CANCEL_PUSH` frame may be sent. #[derive(Debug)] -pub(crate) struct PushController { +pub struct PushController { max_concurent_push: u64, current_max_push_id: u64, // push_streams holds the states of push streams. @@ -157,8 +157,8 @@ pub(crate) struct PushController { } impl PushController { - pub fn new(max_concurent_push: u64, conn_events: Http3ClientEvents) -> Self { - PushController { + pub const fn new(max_concurent_push: u64, conn_events: Http3ClientEvents) -> Self { + Self { max_concurent_push, current_max_push_id: 0, push_streams: ActivePushStreams::new(), @@ -245,12 +245,12 @@ impl PushController { self.check_push_id(push_id)?; - match self.push_streams.get_mut(push_id) { - None => { + self.push_streams.get_mut(push_id).map_or_else( + || { qinfo!("Push has been closed already."); Ok(false) - } - Some(push_state) => match push_state { + }, + |push_state| match push_state { PushState::Init => { *push_state = PushState::OnlyPushStream { stream_id, @@ -273,10 +273,10 @@ impl PushController { Err(Error::HttpId) } }, - } + ) } - fn check_push_id(&mut self, push_id: u64) -> Res<()> { + fn check_push_id(&self, push_id: u64) -> Res<()> { // Check if push id is greater than what we allow. if push_id > self.current_max_push_id { qerror!("Push id is greater than current_max_push_id."); @@ -431,7 +431,7 @@ impl PushController { self.push_streams.clear(); } - pub fn can_receive_push(&self) -> bool { + pub const fn can_receive_push(&self) -> bool { self.max_concurent_push > 0 } @@ -459,13 +459,13 @@ impl PushController { /// `PushHeaderReady` and `PushDataReadable` events or to postpone them if /// a `push_promise` has not been yet received for the stream. #[derive(Debug)] -pub(crate) struct RecvPushEvents { +pub struct RecvPushEvents { push_id: u64, push_handler: Rc>, } impl RecvPushEvents { - pub fn new(push_id: u64, push_handler: Rc>) -> Self { + pub const fn new(push_id: u64, push_handler: Rc>) -> Self { Self { push_id, push_handler, diff --git a/neqo-http3/src/qlog.rs b/neqo-http3/src/qlog.rs index 81f9245a3c..9e2742e159 100644 --- a/neqo-http3/src/qlog.rs +++ b/neqo-http3/src/qlog.rs @@ -10,7 +10,7 @@ use neqo_common::qlog::NeqoQlog; use neqo_transport::StreamId; use qlog::events::{DataRecipient, EventData}; -pub fn h3_data_moved_up(qlog: &mut NeqoQlog, stream_id: StreamId, amount: usize) { +pub fn h3_data_moved_up(qlog: &NeqoQlog, stream_id: StreamId, amount: usize) { qlog.add_event_data(|| { let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved { stream_id: Some(stream_id.as_u64()), @@ -25,7 +25,7 @@ pub fn h3_data_moved_up(qlog: &mut NeqoQlog, stream_id: StreamId, amount: usize) }); } -pub fn h3_data_moved_down(qlog: &mut NeqoQlog, stream_id: StreamId, amount: usize) { +pub fn h3_data_moved_down(qlog: &NeqoQlog, stream_id: StreamId, amount: usize) { qlog.add_event_data(|| { let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved { stream_id: Some(stream_id.as_u64()), diff --git a/neqo-http3/src/qpack_decoder_receiver.rs b/neqo-http3/src/qpack_decoder_receiver.rs index 46b9ca590b..14447905f4 100644 --- a/neqo-http3/src/qpack_decoder_receiver.rs +++ b/neqo-http3/src/qpack_decoder_receiver.rs @@ -12,13 +12,13 @@ use neqo_transport::{Connection, StreamId}; use crate::{CloseType, Error, Http3StreamType, ReceiveOutput, RecvStream, Res, Stream}; #[derive(Debug)] -pub(crate) struct DecoderRecvStream { +pub struct DecoderRecvStream { stream_id: StreamId, decoder: Rc>, } impl DecoderRecvStream { - pub fn new(stream_id: StreamId, decoder: Rc>) -> Self { + pub const fn new(stream_id: StreamId, decoder: Rc>) -> Self { Self { stream_id, decoder } } } diff --git a/neqo-http3/src/qpack_encoder_receiver.rs b/neqo-http3/src/qpack_encoder_receiver.rs index 76c779bcf2..efd59503b1 100644 --- a/neqo-http3/src/qpack_encoder_receiver.rs +++ b/neqo-http3/src/qpack_encoder_receiver.rs @@ -12,13 +12,13 @@ use neqo_transport::{Connection, StreamId}; use crate::{CloseType, Error, Http3StreamType, ReceiveOutput, RecvStream, Res, Stream}; #[derive(Debug)] -pub(crate) struct EncoderRecvStream { +pub struct EncoderRecvStream { stream_id: StreamId, encoder: Rc>, } impl EncoderRecvStream { - pub fn new(stream_id: StreamId, encoder: Rc>) -> Self { + pub const fn new(stream_id: StreamId, encoder: Rc>) -> Self { Self { stream_id, encoder } } } diff --git a/neqo-http3/src/recv_message.rs b/neqo-http3/src/recv_message.rs index 55970849ef..c33633bba5 100644 --- a/neqo-http3/src/recv_message.rs +++ b/neqo-http3/src/recv_message.rs @@ -20,7 +20,7 @@ use crate::{ }; #[allow(clippy::module_name_repetitions)] -pub(crate) struct RecvMessageInfo { +pub struct RecvMessageInfo { pub message_type: MessageType, pub stream_type: Http3StreamType, pub stream_id: StreamId, @@ -66,7 +66,7 @@ struct PushInfo { } #[derive(Debug)] -pub(crate) struct RecvMessage { +pub struct RecvMessage { state: RecvMessageState, message_type: MessageType, stream_type: Http3StreamType, @@ -363,14 +363,14 @@ impl RecvMessage { .recv_closed(self.get_stream_info(), CloseType::Done); } - fn closing(&self) -> bool { + const fn closing(&self) -> bool { matches!( self.state, RecvMessageState::ClosePending | RecvMessageState::Closed ) } - fn get_stream_info(&self) -> Http3StreamInfo { + const fn get_stream_info(&self) -> Http3StreamInfo { Http3StreamInfo::new(self.stream_id, Http3StreamType::Http) } } diff --git a/neqo-http3/src/request_target.rs b/neqo-http3/src/request_target.rs index 28bc22ac2d..e43406e5d6 100644 --- a/neqo-http3/src/request_target.rs +++ b/neqo-http3/src/request_target.rs @@ -38,7 +38,7 @@ impl RequestTarget for RefRequestTarget<'_, '_, '_> { impl<'s, 'a, 'p> RefRequestTarget<'s, 'a, 'p> { #[must_use] - pub fn new(scheme: &'s str, authority: &'a str, path: &'p str) -> Self { + pub const fn new(scheme: &'s str, authority: &'a str, path: &'p str) -> Self { Self { scheme, authority, diff --git a/neqo-http3/src/send_message.rs b/neqo-http3/src/send_message.rs index 6553d20432..378786d12f 100644 --- a/neqo-http3/src/send_message.rs +++ b/neqo-http3/src/send_message.rs @@ -27,7 +27,7 @@ const MAX_DATA_HEADER_SIZE_5_LIMIT: usize = MAX_DATA_HEADER_SIZE_5 + 9; // 10737 /// A HTTP message, request and response, consists of headers, optional data and an optional /// trailer header block. This state machine does not reflect what was already sent to the -/// transport layer but only reflect what has been supplied to the `SendMessage`.It is +/// transport layer but only reflect what has been supplied to the `SendMessage`. It is /// represented by the following states: /// `WaitingForHeaders` - the headers have not been supplied yet. In this state only a /// request/response header can be added. When headers are supplied @@ -42,7 +42,6 @@ const MAX_DATA_HEADER_SIZE_5_LIMIT: usize = MAX_DATA_HEADER_SIZE_5 + 9; // 10737 /// supply only a fin. /// `Done` - in this state no more data or headers can be added. This state is entered when the /// message is closed. - #[derive(Debug, PartialEq)] enum MessageState { WaitingForHeaders, @@ -103,7 +102,7 @@ impl MessageState { } #[derive(Debug)] -pub(crate) struct SendMessage { +pub struct SendMessage { state: MessageState, message_type: MessageType, stream_type: Http3StreamType, @@ -314,7 +313,7 @@ impl SendStream for SendMessage { impl HttpSendStream for SendMessage { fn send_headers(&mut self, headers: &[Header], conn: &mut Connection) -> Res<()> { self.state.new_headers(headers, self.message_type)?; - let buf = SendMessage::encode( + let buf = Self::encode( &mut self.encoder.borrow_mut(), headers, conn, diff --git a/neqo-http3/src/server.rs b/neqo-http3/src/server.rs index 4cc31b597a..47a119b877 100644 --- a/neqo-http3/src/server.rs +++ b/neqo-http3/src/server.rs @@ -84,7 +84,7 @@ impl Http3Server { self.server.set_qlog_dir(dir); } - pub fn set_validation(&mut self, v: ValidateAddress) { + pub fn set_validation(&self, v: ValidateAddress) { self.server.set_validation(v); } @@ -130,6 +130,9 @@ impl Http3Server { /// Process HTTP3 layer. fn process_http3(&mut self, now: Instant) { qtrace!([self], "Process http3 internal."); + // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable + // types. + #[allow(clippy::mutable_key_type)] let mut active_conns = self.server.active_connections(); active_conns.extend( self.http3_handlers @@ -139,12 +142,12 @@ impl Http3Server { .cloned(), ); - for mut conn in active_conns { - self.process_events(&mut conn, now); + for conn in active_conns { + self.process_events(&conn, now); } } - fn process_events(&mut self, conn: &mut ActiveConnectionRef, now: Instant) { + fn process_events(&mut self, conn: &ActiveConnectionRef, now: Instant) { let mut remove = false; let http3_parameters = &self.http3_parameters; { @@ -175,7 +178,7 @@ impl Http3Server { conn, handler, now, - &mut self.events, + &self.events, ); } Http3ServerConnEvent::DataWritable { stream_info } => self @@ -246,7 +249,7 @@ impl Http3Server { /// Get all current events. Best used just in debug/testing code, use /// `next_event` instead. - pub fn events(&mut self) -> impl Iterator { + pub fn events(&self) -> impl Iterator { self.events.events() } @@ -259,17 +262,18 @@ impl Http3Server { /// Get events that indicate state changes on the connection. This method /// correctly handles cases where handling one event can obsolete /// previously-queued events, or cause new events to be generated. - pub fn next_event(&mut self) -> Option { + #[must_use] + pub fn next_event(&self) -> Option { self.events.next_event() } } fn prepare_data( stream_info: Http3StreamInfo, handler_borrowed: &mut RefMut, - conn: &mut ActiveConnectionRef, + conn: &ActiveConnectionRef, handler: &HandlerRef, now: Instant, - events: &mut Http3ServerEvents, + events: &Http3ServerEvents, ) { loop { let mut data = vec![0; MAX_EVENT_DATA_SIZE]; @@ -352,13 +356,13 @@ mod tests { create_server(http3params(DEFAULT_SETTINGS)) } - fn assert_closed(hconn: &mut Http3Server, expected: &Error) { + fn assert_closed(hconn: &Http3Server, expected: &Error) { let err = CloseReason::Application(expected.code()); let closed = |e| matches!(e, Http3ServerEvent::StateChange{ state: Http3State::Closing(e) | Http3State::Closed(e), .. } if e == err); assert!(hconn.events().any(closed)); } - fn assert_connected(hconn: &mut Http3Server) { + fn assert_connected(hconn: &Http3Server) { let connected = |e| { matches!( e, @@ -371,7 +375,7 @@ mod tests { assert!(hconn.events().any(connected)); } - fn assert_not_closed(hconn: &mut Http3Server) { + fn assert_not_closed(hconn: &Http3Server) { let closed = |e| { matches!( e, @@ -582,7 +586,7 @@ mod tests { peer_conn.stream_close_send(control).unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } // Server: test missing SETTINGS frame @@ -597,7 +601,7 @@ mod tests { assert_eq!(sent, Ok(4)); let out = neqo_trans_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpMissingSettings); + assert_closed(&hconn, &Error::HttpMissingSettings); } // Server: receiving SETTINGS frame twice causes connection close @@ -609,7 +613,7 @@ mod tests { peer_conn.control_send(&[0x4, 0x6, 0x1, 0x40, 0x64, 0x7, 0x40, 0x64]); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpFrameUnexpected); + assert_closed(&hconn, &Error::HttpFrameUnexpected); } fn priority_update_check_id(stream_id: StreamId, valid: bool) { @@ -626,9 +630,9 @@ mod tests { hconn.process(out.as_dgram_ref(), now()); // check if the given connection got closed on invalid stream ids if valid { - assert_not_closed(&mut hconn); + assert_not_closed(&hconn); } else { - assert_closed(&mut hconn, &Error::HttpId); + assert_closed(&hconn, &Error::HttpId); } } @@ -667,7 +671,7 @@ mod tests { let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpFrameUnexpected); + assert_closed(&hconn, &Error::HttpFrameUnexpected); } // send DATA frame on a control stream @@ -719,7 +723,7 @@ mod tests { } } assert!(stop_sending_event_found); - assert_not_closed(&mut hconn); + assert_not_closed(&hconn); } // Server: receiving a push stream on a server should cause WrongStreamDirection @@ -733,7 +737,7 @@ mod tests { let out = peer_conn.process(None, now()); let out = hconn.process(out.as_dgram_ref(), now()); mem::drop(peer_conn.conn.process(out.as_dgram_ref(), now())); - assert_closed(&mut hconn, &Error::HttpStreamCreation); + assert_closed(&hconn, &Error::HttpStreamCreation); } /// Test reading of a slowly streamed frame. bytes are received one by one @@ -781,7 +785,7 @@ mod tests { let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_not_closed(&mut hconn); + assert_not_closed(&hconn); // Now test PushPromise sent = peer_conn.stream_send(control_stream, &[0x5]); @@ -820,7 +824,7 @@ mod tests { hconn.process(out.as_dgram_ref(), now()); // PUSH_PROMISE on a control stream will cause an error - assert_closed(&mut hconn, &Error::HttpFrameUnexpected); + assert_closed(&hconn, &Error::HttpFrameUnexpected); } // Test reading of a slowly streamed frame. bytes are received one by one @@ -835,7 +839,7 @@ mod tests { let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpFrame); + assert_closed(&hconn, &Error::HttpFrame); } const REQUEST_WITH_BODY: &[u8] = &[ @@ -897,11 +901,7 @@ mod tests { assert!(!fin); headers_frames += 1; } - Http3ServerEvent::Data { - mut stream, - data, - fin, - } => { + Http3ServerEvent::Data { stream, data, fin } => { assert_eq!(data, REQUEST_BODY); assert!(fin); stream @@ -943,7 +943,7 @@ mod tests { while let Some(event) = hconn.next_event() { match event { Http3ServerEvent::Headers { - mut stream, + stream, headers, fin, } => { @@ -1021,7 +1021,7 @@ mod tests { while let Some(event) = hconn.next_event() { match event { Http3ServerEvent::Headers { - mut stream, + stream, headers, fin, } => { @@ -1079,7 +1079,7 @@ mod tests { .unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } // Server: Test that the connection will be closed if the client side encoder stream @@ -1092,7 +1092,7 @@ mod tests { .unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } // Server: Test that the connection will be closed if the client side decoder stream @@ -1105,7 +1105,7 @@ mod tests { .unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } // Server: Test that the connection will be closed if the local control stream @@ -1119,7 +1119,7 @@ mod tests { .unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } // Server: Test that the connection will be closed if the server side encoder stream @@ -1132,7 +1132,7 @@ mod tests { .unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } // Server: Test that the connection will be closed if the server side decoder stream @@ -1145,7 +1145,7 @@ mod tests { .unwrap(); let out = peer_conn.process(None, now()); hconn.process(out.as_dgram_ref(), now()); - assert_closed(&mut hconn, &Error::HttpClosedCriticalStream); + assert_closed(&hconn, &Error::HttpClosedCriticalStream); } /// Perform a handshake, then another with the token from the first. diff --git a/neqo-http3/src/server_connection_events.rs b/neqo-http3/src/server_connection_events.rs index cbc8e6d56e..9bac2cbdf6 100644 --- a/neqo-http3/src/server_connection_events.rs +++ b/neqo-http3/src/server_connection_events.rs @@ -16,7 +16,7 @@ use crate::{ }; #[derive(Debug, PartialEq, Eq, Clone)] -pub(crate) enum Http3ServerConnEvent { +pub enum Http3ServerConnEvent { /// Headers are ready. Headers { stream_info: Http3StreamInfo, @@ -62,7 +62,7 @@ pub(crate) enum Http3ServerConnEvent { } #[derive(Debug, Default, Clone)] -pub(crate) struct Http3ServerConnEvents { +pub struct Http3ServerConnEvents { events: Rc>>, } diff --git a/neqo-http3/src/server_events.rs b/neqo-http3/src/server_events.rs index 119d9f9f39..82528e13b2 100644 --- a/neqo-http3/src/server_events.rs +++ b/neqo-http3/src/server_events.rs @@ -43,7 +43,7 @@ impl std::hash::Hash for StreamHandler { fn hash(&self, state: &mut H) { self.conn.hash(state); state.write_u64(self.stream_info.stream_id().as_u64()); - state.finish(); + _ = state.finish(); } } @@ -56,7 +56,7 @@ impl PartialEq for StreamHandler { impl Eq for StreamHandler {} impl StreamHandler { - pub fn stream_id(&self) -> StreamId { + pub const fn stream_id(&self) -> StreamId { self.stream_info.stream_id() } @@ -65,7 +65,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn send_headers(&mut self, headers: &[Header]) -> Res<()> { + pub fn send_headers(&self, headers: &[Header]) -> Res<()> { self.handler.borrow_mut().send_headers( self.stream_id(), headers, @@ -78,7 +78,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn send_data(&mut self, buf: &[u8]) -> Res { + pub fn send_data(&self, buf: &[u8]) -> Res { self.handler .borrow_mut() .send_data(self.stream_id(), buf, &mut self.conn.borrow_mut()) @@ -91,7 +91,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn available(&mut self) -> Res { + pub fn available(&self) -> Res { let stream_id = self.stream_id(); let n = self.conn.borrow_mut().stream_avail_send_space(stream_id)?; Ok(n) @@ -102,7 +102,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn stream_close_send(&mut self) -> Res<()> { + pub fn stream_close_send(&self) -> Res<()> { self.handler .borrow_mut() .stream_close_send(self.stream_id(), &mut self.conn.borrow_mut()) @@ -113,7 +113,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn stream_stop_sending(&mut self, app_error: AppError) -> Res<()> { + pub fn stream_stop_sending(&self, app_error: AppError) -> Res<()> { qdebug!( [self], "stop sending stream_id:{} error:{}.", @@ -132,7 +132,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn stream_reset_send(&mut self, app_error: AppError) -> Res<()> { + pub fn stream_reset_send(&self, app_error: AppError) -> Res<()> { qdebug!( [self], "reset send stream_id:{} error:{}.", @@ -151,7 +151,7 @@ impl StreamHandler { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore - pub fn cancel_fetch(&mut self, app_error: AppError) -> Res<()> { + pub fn cancel_fetch(&self, app_error: AppError) -> Res<()> { qdebug!([self], "reset error:{}.", app_error); self.handler.borrow_mut().cancel_fetch( self.stream_info.stream_id(), @@ -173,7 +173,7 @@ impl ::std::fmt::Display for Http3OrWebTransportStream { } impl Http3OrWebTransportStream { - pub(crate) fn new( + pub(crate) const fn new( conn: ActiveConnectionRef, handler: Rc>, stream_info: Http3StreamInfo, @@ -192,7 +192,7 @@ impl Http3OrWebTransportStream { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn send_headers(&mut self, headers: &[Header]) -> Res<()> { + pub fn send_headers(&self, headers: &[Header]) -> Res<()> { self.stream_handler.send_headers(headers) } @@ -201,7 +201,7 @@ impl Http3OrWebTransportStream { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn send_data(&mut self, data: &[u8]) -> Res { + pub fn send_data(&self, data: &[u8]) -> Res { qdebug!([self], "Set new response."); self.stream_handler.send_data(data) } @@ -211,7 +211,7 @@ impl Http3OrWebTransportStream { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn stream_close_send(&mut self) -> Res<()> { + pub fn stream_close_send(&self) -> Res<()> { qdebug!([self], "Set new response."); self.stream_handler.stream_close_send() } @@ -234,7 +234,7 @@ impl DerefMut for Http3OrWebTransportStream { impl std::hash::Hash for Http3OrWebTransportStream { fn hash(&self, state: &mut H) { self.stream_handler.hash(state); - state.finish(); + _ = state.finish(); } } @@ -258,7 +258,7 @@ impl ::std::fmt::Display for WebTransportRequest { } impl WebTransportRequest { - pub(crate) fn new( + pub(crate) const fn new( conn: ActiveConnectionRef, handler: Rc>, stream_id: StreamId, @@ -282,7 +282,7 @@ impl WebTransportRequest { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn response(&mut self, accept: &WebTransportSessionAcceptAction) -> Res<()> { + pub fn response(&self, accept: &WebTransportSessionAcceptAction) -> Res<()> { qdebug!([self], "Set a response for a WebTransport session."); self.stream_handler .handler @@ -299,7 +299,7 @@ impl WebTransportRequest { /// It may return `InvalidStreamId` if a stream does not exist anymore. /// Also return an error if the stream was closed on the transport layer, /// but that information is not yet consumed on the http/3 layer. - pub fn close_session(&mut self, error: u32, message: &str) -> Res<()> { + pub fn close_session(&self, error: u32, message: &str) -> Res<()> { self.stream_handler .handler .borrow_mut() @@ -312,7 +312,7 @@ impl WebTransportRequest { } #[must_use] - pub fn stream_id(&self) -> StreamId { + pub const fn stream_id(&self) -> StreamId { self.stream_handler.stream_id() } @@ -321,7 +321,7 @@ impl WebTransportRequest { /// # Errors /// /// It may return `InvalidStreamId` if a stream does not exist anymore. - pub fn create_stream(&mut self, stream_type: StreamType) -> Res { + pub fn create_stream(&self, stream_type: StreamType) -> Res { let session_id = self.stream_handler.stream_id(); let id = self .stream_handler @@ -347,7 +347,7 @@ impl WebTransportRequest { /// It may return `InvalidStreamId` if a stream does not exist anymore. /// The function returns `TooMuchData` if the supply buffer is bigger than /// the allowed remote datagram size. - pub fn send_datagram(&mut self, buf: &[u8], id: impl Into) -> Res<()> { + pub fn send_datagram(&self, buf: &[u8], id: impl Into) -> Res<()> { let session_id = self.stream_handler.stream_id(); self.stream_handler .handler @@ -403,7 +403,7 @@ impl DerefMut for WebTransportRequest { impl std::hash::Hash for WebTransportRequest { fn hash(&self, state: &mut H) { self.stream_handler.hash(state); - state.finish(); + _ = state.finish(); } } diff --git a/neqo-http3/src/settings.rs b/neqo-http3/src/settings.rs index 9cd4b994b7..2592249804 100644 --- a/neqo-http3/src/settings.rs +++ b/neqo-http3/src/settings.rs @@ -41,7 +41,7 @@ pub enum HSettingType { EnableH3Datagram, } -fn hsetting_default(setting_type: HSettingType) -> u64 { +const fn hsetting_default(setting_type: HSettingType) -> u64 { match setting_type { HSettingType::MaxHeaderListSize => 1 << 62, HSettingType::MaxTableCapacity @@ -59,7 +59,7 @@ pub struct HSetting { impl HSetting { #[must_use] - pub fn new(setting_type: HSettingType, value: u64) -> Self { + pub const fn new(setting_type: HSettingType, value: u64) -> Self { Self { setting_type, value, @@ -82,10 +82,10 @@ impl HSettings { #[must_use] pub fn get(&self, setting: HSettingType) -> u64 { - match self.settings.iter().find(|s| s.setting_type == setting) { - Some(v) => v.value, - None => hsetting_default(setting), - } + self.settings + .iter() + .find(|s| s.setting_type == setting) + .map_or_else(|| hsetting_default(setting), |v| v.value) } pub fn encode_frame_contents(&self, enc: &mut Encoder) { @@ -226,7 +226,7 @@ pub struct HttpZeroRttChecker { impl HttpZeroRttChecker { /// Right now we only have QPACK settings, so that is all this takes. #[must_use] - pub fn new(settings: Http3Parameters) -> Self { + pub const fn new(settings: Http3Parameters) -> Self { Self { settings } } diff --git a/neqo-http3/src/stream_type_reader.rs b/neqo-http3/src/stream_type_reader.rs index f36181d3b1..556969df29 100644 --- a/neqo-http3/src/stream_type_reader.rs +++ b/neqo-http3/src/stream_type_reader.rs @@ -15,12 +15,12 @@ use crate::{ Error, Http3StreamType, ReceiveOutput, RecvStream, Res, Stream, }; -pub(crate) const HTTP3_UNI_STREAM_TYPE_PUSH: u64 = 0x1; -pub(crate) const WEBTRANSPORT_UNI_STREAM: u64 = 0x54; -pub(crate) const WEBTRANSPORT_STREAM: u64 = 0x41; +pub const HTTP3_UNI_STREAM_TYPE_PUSH: u64 = 0x1; +pub const WEBTRANSPORT_UNI_STREAM: u64 = 0x54; +pub const WEBTRANSPORT_STREAM: u64 = 0x41; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum NewStreamType { +pub enum NewStreamType { Control, Decoder, Encoder, @@ -39,31 +39,23 @@ impl NewStreamType { /// /// Push streams received by the server are not allowed and this function will return /// `HttpStreamCreation` error. - fn final_stream_type( + const fn final_stream_type( stream_type: u64, trans_stream_type: StreamType, role: Role, - ) -> Res> { + ) -> Res> { match (stream_type, trans_stream_type, role) { - (HTTP3_UNI_STREAM_TYPE_CONTROL, StreamType::UniDi, _) => { - Ok(Some(NewStreamType::Control)) - } - (QPACK_UNI_STREAM_TYPE_ENCODER, StreamType::UniDi, _) => { - Ok(Some(NewStreamType::Decoder)) - } - (QPACK_UNI_STREAM_TYPE_DECODER, StreamType::UniDi, _) => { - Ok(Some(NewStreamType::Encoder)) - } + (HTTP3_UNI_STREAM_TYPE_CONTROL, StreamType::UniDi, _) => Ok(Some(Self::Control)), + (QPACK_UNI_STREAM_TYPE_ENCODER, StreamType::UniDi, _) => Ok(Some(Self::Decoder)), + (QPACK_UNI_STREAM_TYPE_DECODER, StreamType::UniDi, _) => Ok(Some(Self::Encoder)), (HTTP3_UNI_STREAM_TYPE_PUSH, StreamType::UniDi, Role::Client) | (WEBTRANSPORT_UNI_STREAM, StreamType::UniDi, _) | (WEBTRANSPORT_STREAM, StreamType::BiDi, _) => Ok(None), - (H3_FRAME_TYPE_HEADERS, StreamType::BiDi, Role::Server) => { - Ok(Some(NewStreamType::Http)) - } + (H3_FRAME_TYPE_HEADERS, StreamType::BiDi, Role::Server) => Ok(Some(Self::Http)), (_, StreamType::BiDi, Role::Server) => Err(Error::HttpFrame), (HTTP3_UNI_STREAM_TYPE_PUSH, StreamType::UniDi, Role::Server) | (_, StreamType::BiDi, Role::Client) => Err(Error::HttpStreamCreation), - _ => Ok(Some(NewStreamType::Unknown)), + _ => Ok(Some(Self::Unknown)), } } } @@ -76,7 +68,7 @@ impl NewStreamType { /// is identified by the type and `PushId`. After reading the type in the `ReadType` state, /// `NewStreamHeadReader` changes to `ReadId` state and from there to `Done` state #[derive(Debug)] -pub(crate) enum NewStreamHeadReader { +pub enum NewStreamHeadReader { ReadType { role: Role, reader: IncrementalDecoderUint, @@ -92,7 +84,7 @@ pub(crate) enum NewStreamHeadReader { impl NewStreamHeadReader { pub fn new(stream_id: StreamId, role: Role) -> Self { - NewStreamHeadReader::ReadType { + Self::ReadType { role, reader: IncrementalDecoderUint::default(), stream_id, @@ -100,10 +92,10 @@ impl NewStreamHeadReader { } fn read(&mut self, conn: &mut Connection) -> Res<(Option, bool)> { - if let NewStreamHeadReader::ReadType { + if let Self::ReadType { reader, stream_id, .. } - | NewStreamHeadReader::ReadId { + | Self::ReadId { reader, stream_id, .. } = self { @@ -130,7 +122,7 @@ impl NewStreamHeadReader { let (output, fin) = self.read(conn)?; let Some(output) = output else { if fin { - *self = NewStreamHeadReader::Done; + *self = Self::Done; return Err(Error::HttpStreamCreation); } return Ok(None); @@ -138,7 +130,7 @@ impl NewStreamHeadReader { qtrace!("Decoded uint {}", output); match self { - NewStreamHeadReader::ReadType { + Self::ReadType { role, stream_id, .. } => { // final_stream_type may return: @@ -152,21 +144,21 @@ impl NewStreamHeadReader { NewStreamType::final_stream_type(output, stream_id.stream_type(), *role); match (&final_type, fin) { (Err(_), _) => { - *self = NewStreamHeadReader::Done; + *self = Self::Done; return final_type; } (Ok(t), true) => { - *self = NewStreamHeadReader::Done; + *self = Self::Done; return Self::map_stream_fin(*t); } (Ok(Some(t)), false) => { qtrace!("Decoded stream type {:?}", *t); - *self = NewStreamHeadReader::Done; + *self = Self::Done; return final_type; } (Ok(None), false) => { // This is a push stream and it needs more data to be decoded. - *self = NewStreamHeadReader::ReadId { + *self = Self::ReadId { reader: IncrementalDecoderUint::default(), stream_id: *stream_id, stream_type: output, @@ -174,9 +166,9 @@ impl NewStreamHeadReader { } } } - NewStreamHeadReader::ReadId { stream_type, .. } => { + Self::ReadId { stream_type, .. } => { let is_push = *stream_type == HTTP3_UNI_STREAM_TYPE_PUSH; - *self = NewStreamHeadReader::Done; + *self = Self::Done; qtrace!("New Stream stream push_id={}", output); if fin { return Err(Error::HttpGeneralProtocol); @@ -187,7 +179,7 @@ impl NewStreamHeadReader { Ok(Some(NewStreamType::WebTransportStream(output))) }; } - NewStreamHeadReader::Done => { + Self::Done => { unreachable!("Cannot be in state NewStreamHeadReader::Done"); } } @@ -208,8 +200,8 @@ impl NewStreamHeadReader { } } - fn done(&self) -> bool { - matches!(self, NewStreamHeadReader::Done) + const fn done(&self) -> bool { + matches!(self, Self::Done) } } @@ -221,7 +213,7 @@ impl Stream for NewStreamHeadReader { impl RecvStream for NewStreamHeadReader { fn reset(&mut self, _close_type: CloseType) -> Res<()> { - *self = NewStreamHeadReader::Done; + *self = Self::Done; Ok(()) } diff --git a/neqo-http3/tests/httpconn.rs b/neqo-http3/tests/httpconn.rs index 801668af9f..9e9d716adf 100644 --- a/neqo-http3/tests/httpconn.rs +++ b/neqo-http3/tests/httpconn.rs @@ -22,7 +22,7 @@ use test_fixture::*; const RESPONSE_DATA: &[u8] = &[0x61, 0x62, 0x63]; -fn receive_request(server: &mut Http3Server) -> Option { +fn receive_request(server: &Http3Server) -> Option { while let Some(event) = server.next_event() { if let Http3ServerEvent::Headers { stream, @@ -47,7 +47,7 @@ fn receive_request(server: &mut Http3Server) -> Option; rel=preload; as=style"), @@ -240,7 +239,7 @@ fn test_103_response() { }; assert!(hconn_c.events().any(info_headers_event)); - set_response(&mut request); + set_response(&request); let out = hconn_s.process(None, now()); mem::drop(hconn_c.process(out.as_dgram_ref(), now())); process_client_events(&mut hconn_c); @@ -273,7 +272,7 @@ fn test_data_writable_events_low_watermark() -> Result<(), Box Option { +fn receive_request(server: &Http3Server) -> Option { while let Some(event) = server.next_event() { if let Http3ServerEvent::Headers { stream, @@ -61,18 +61,18 @@ fn receive_request(server: &mut Http3Server) -> Option Result<(), Error> { +fn send_trailers(request: &Http3OrWebTransportStream) -> Result<(), Error> { request.send_headers(&[ Header::new("something1", "something"), Header::new("something2", "3"), ]) } -fn send_informational_headers(request: &mut Http3OrWebTransportStream) -> Result<(), Error> { +fn send_informational_headers(request: &Http3OrWebTransportStream) -> Result<(), Error> { request.send_headers(response_header_103()) } -fn send_headers(request: &mut Http3OrWebTransportStream) -> Result<(), Error> { +fn send_headers(request: &Http3OrWebTransportStream) -> Result<(), Error> { request.send_headers(&[ Header::new(":status", "200"), Header::new("content-length", "3"), @@ -158,17 +158,17 @@ fn connect_send_and_receive_request() -> (Http3Client, Http3Server, Http3OrWebTr hconn_c.stream_close_send(req).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - let request = receive_request(&mut hconn_s).unwrap(); + let request = receive_request(&hconn_s).unwrap(); (hconn_c, hconn_s, request) } #[test] fn response_trailers1() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); - send_trailers(&mut request).unwrap(); + send_trailers(&request).unwrap(); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); process_client_events(&mut hconn_c); @@ -176,11 +176,11 @@ fn response_trailers1() { #[test] fn response_trailers2() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - send_trailers(&mut request).unwrap(); + send_trailers(&request).unwrap(); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); process_client_events(&mut hconn_c); @@ -188,11 +188,11 @@ fn response_trailers2() { #[test] fn response_trailers3() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - send_trailers(&mut request).unwrap(); + send_trailers(&request).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); @@ -201,10 +201,10 @@ fn response_trailers3() { #[test] fn response_trailers_no_data() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); request.send_headers(response_header_no_data()).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - send_trailers(&mut request).unwrap(); + send_trailers(&request).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); @@ -213,14 +213,14 @@ fn response_trailers_no_data() { #[test] fn multiple_response_trailers() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - send_trailers(&mut request).unwrap(); + send_trailers(&request).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - assert_eq!(send_trailers(&mut request), Err(Error::InvalidInput)); + assert_eq!(send_trailers(&request), Err(Error::InvalidInput)); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); @@ -229,11 +229,11 @@ fn multiple_response_trailers() { #[test] fn data_after_trailer() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); - send_trailers(&mut request).unwrap(); + send_trailers(&request).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); assert_eq!(request.send_data(RESPONSE_DATA), Err(Error::InvalidInput)); @@ -245,12 +245,12 @@ fn data_after_trailer() { #[test] fn trailers_after_close() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); request.stream_close_send().unwrap(); - assert_eq!(send_trailers(&mut request), Err(Error::InvalidStreamId)); + assert_eq!(send_trailers(&request), Err(Error::InvalidStreamId)); exchange_packets(&mut hconn_c, &mut hconn_s); process_client_events(&mut hconn_c); @@ -258,7 +258,7 @@ fn trailers_after_close() { #[test] fn multiple_response_headers() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); request.send_headers(response_header_no_data()).unwrap(); assert_eq!( @@ -273,11 +273,11 @@ fn multiple_response_headers() { #[test] fn informational_after_response_headers() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); request.send_headers(response_header_no_data()).unwrap(); assert_eq!( - send_informational_headers(&mut request), + send_informational_headers(&request), Err(Error::InvalidHeader) ); @@ -288,12 +288,12 @@ fn informational_after_response_headers() { #[test] fn data_after_informational() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_informational_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_informational_headers(&request).unwrap(); assert_eq!(request.send_data(RESPONSE_DATA), Err(Error::InvalidInput)); - send_headers(&mut request).unwrap(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); @@ -302,8 +302,8 @@ fn data_after_informational() { #[test] fn non_trailers_headers_after_data() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); - send_headers(&mut request).unwrap(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); @@ -319,10 +319,10 @@ fn non_trailers_headers_after_data() { #[test] fn data_before_headers() { - let (mut hconn_c, mut hconn_s, mut request) = connect_send_and_receive_request(); + let (mut hconn_c, mut hconn_s, request) = connect_send_and_receive_request(); assert_eq!(request.send_data(RESPONSE_DATA), Err(Error::InvalidInput)); - send_headers(&mut request).unwrap(); + send_headers(&request).unwrap(); request.send_data(RESPONSE_DATA).unwrap(); request.stream_close_send().unwrap(); exchange_packets(&mut hconn_c, &mut hconn_s); diff --git a/neqo-http3/tests/webtransport.rs b/neqo-http3/tests/webtransport.rs index b1e18a5a98..d178b23539 100644 --- a/neqo-http3/tests/webtransport.rs +++ b/neqo-http3/tests/webtransport.rs @@ -92,7 +92,7 @@ fn create_wt_session(client: &mut Http3Client, server: &mut Http3Server) -> WebT while let Some(event) = server.next_event() { match event { Http3ServerEvent::WebTransport(WebTransportServerEvent::NewSession { - mut session, + session, headers, }) => { assert!( @@ -151,7 +151,7 @@ fn send_data_client( fn send_data_server( client: &mut Http3Client, server: &mut Http3Server, - wt_stream: &mut Http3OrWebTransportStream, + wt_stream: &Http3OrWebTransportStream, data: &[u8], ) { assert_eq!(wt_stream.send_data(data).unwrap(), data.len()); @@ -254,7 +254,7 @@ fn wt_client_stream_bidi() { .webtransport_create_stream(wt_session.stream_id(), StreamType::BiDi) .unwrap(); send_data_client(&mut client, &mut server, wt_client_stream, BUF_CLIENT); - let mut wt_server_stream = receive_data_server( + let wt_server_stream = receive_data_server( &mut client, &mut server, wt_client_stream, @@ -262,7 +262,7 @@ fn wt_client_stream_bidi() { BUF_CLIENT, false, ); - send_data_server(&mut client, &mut server, &mut wt_server_stream, BUF_SERVER); + send_data_server(&mut client, &mut server, &wt_server_stream, BUF_SERVER); receive_data_client(&mut client, wt_client_stream, false, BUF_SERVER, false); } @@ -271,9 +271,9 @@ fn wt_server_stream_uni() { const BUF_SERVER: &[u8] = &[2; 30]; let (mut client, mut server) = connect(); - let mut wt_session = create_wt_session(&mut client, &mut server); - let mut wt_server_stream = wt_session.create_stream(StreamType::UniDi).unwrap(); - send_data_server(&mut client, &mut server, &mut wt_server_stream, BUF_SERVER); + let wt_session = create_wt_session(&mut client, &mut server); + let wt_server_stream = wt_session.create_stream(StreamType::UniDi).unwrap(); + send_data_server(&mut client, &mut server, &wt_server_stream, BUF_SERVER); receive_data_client( &mut client, wt_server_stream.stream_id(), @@ -289,9 +289,9 @@ fn wt_server_stream_bidi() { const BUF_SERVER: &[u8] = &[1; 20]; let (mut client, mut server) = connect(); - let mut wt_session = create_wt_session(&mut client, &mut server); - let mut wt_server_stream = wt_session.create_stream(StreamType::BiDi).unwrap(); - send_data_server(&mut client, &mut server, &mut wt_server_stream, BUF_SERVER); + let wt_session = create_wt_session(&mut client, &mut server); + let wt_server_stream = wt_session.create_stream(StreamType::BiDi).unwrap(); + send_data_server(&mut client, &mut server, &wt_server_stream, BUF_SERVER); receive_data_client( &mut client, wt_server_stream.stream_id(), diff --git a/neqo-qpack/Cargo.toml b/neqo-qpack/Cargo.toml index a221c854ae..74fe823e4b 100644 --- a/neqo-qpack/Cargo.toml +++ b/neqo-qpack/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/neqo-qpack/src/decoder.rs b/neqo-qpack/src/decoder.rs index b2cfb6629a..c783cbb0bb 100644 --- a/neqo-qpack/src/decoder.rs +++ b/neqo-qpack/src/decoder.rs @@ -58,12 +58,12 @@ impl QPackDecoder { } #[must_use] - fn capacity(&self) -> u64 { + const fn capacity(&self) -> u64 { self.table.capacity() } #[must_use] - pub fn get_max_table_size(&self) -> u64 { + pub const fn get_max_table_size(&self) -> u64 { self.max_table_size } @@ -259,7 +259,7 @@ impl QPackDecoder { } #[must_use] - pub fn local_stream_id(&self) -> Option { + pub const fn local_stream_id(&self) -> Option { self.local_stream_id } diff --git a/neqo-qpack/src/decoder_instructions.rs b/neqo-qpack/src/decoder_instructions.rs index 029cd61db6..864a693665 100644 --- a/neqo-qpack/src/decoder_instructions.rs +++ b/neqo-qpack/src/decoder_instructions.rs @@ -76,7 +76,7 @@ impl ::std::fmt::Display for DecoderInstructionReader { } impl DecoderInstructionReader { - pub fn new() -> Self { + pub const fn new() -> Self { Self { state: DecoderInstructionReaderState::ReadInstruction, instruction: DecoderInstruction::NoInstruction, diff --git a/neqo-qpack/src/encoder.rs b/neqo-qpack/src/encoder.rs index c90570ccdc..2869ddfbfa 100644 --- a/neqo-qpack/src/encoder.rs +++ b/neqo-qpack/src/encoder.rs @@ -31,7 +31,7 @@ enum LocalStreamState { } impl LocalStreamState { - pub fn stream_id(&self) -> Option { + pub const fn stream_id(&self) -> Option { match self { Self::NoStream => None, Self::Uninitialized(stream_id) | Self::Initialized(stream_id) => Some(*stream_id), @@ -202,11 +202,7 @@ impl QPackEncoder { } } - fn call_instruction( - &mut self, - instruction: DecoderInstruction, - qlog: &mut NeqoQlog, - ) -> Res<()> { + fn call_instruction(&mut self, instruction: DecoderInstruction, qlog: &NeqoQlog) -> Res<()> { qdebug!([self], "call intruction {:?}", instruction); match instruction { DecoderInstruction::InsertCountIncrement { increment } => { @@ -344,15 +340,14 @@ impl QPackEncoder { } fn is_stream_blocker(&self, stream_id: StreamId) -> bool { - if let Some(hb_list) = self.unacked_header_blocks.get(&stream_id) { - debug_assert!(!hb_list.is_empty()); - match hb_list.iter().flatten().max() { - Some(max_ref) => *max_ref >= self.table.get_acked_inserts_cnt(), - None => false, - } - } else { - false - } + self.unacked_header_blocks + .get(&stream_id) + .map_or(false, |hb_list| { + debug_assert!(!hb_list.is_empty()); + hb_list.iter().flatten().max().map_or(false, |max_ref| { + *max_ref >= self.table.get_acked_inserts_cnt() + }) + }) } /// Encodes headers @@ -373,20 +368,17 @@ impl QPackEncoder { ) -> HeaderEncoder { qdebug!([self], "encoding headers."); - let mut encoder_blocked = false; // Try to send capacity instructions if present. - if self.send_encoder_updates(conn).is_err() { - // This code doesn't try to deal with errors, it just tries - // to write to the encoder stream AND if it can't uses - // literal instructions. - // The errors can be: - // 1) `EncoderStreamBlocked` - this is an error that can occur. - // 2) `InternalError` - this is unexpected error. - // 3) `ClosedCriticalStream` - this is error that should close the HTTP/3 session. - // The last 2 errors are ignored here and will be picked up - // by the main loop. - encoder_blocked = true; - } + // This code doesn't try to deal with errors, it just tries + // to write to the encoder stream AND if it can't uses + // literal instructions. + // The errors can be: + // 1) `EncoderStreamBlocked` - this is an error that can occur. + // 2) `InternalError` - this is unexpected error. + // 3) `ClosedCriticalStream` - this is error that should close the HTTP/3 session. + // The last 2 errors are ignored here and will be picked up + // by the main loop. + let mut encoder_blocked = self.send_encoder_updates(conn).is_err(); let mut encoded_h = HeaderEncoder::new(self.table.base(), self.use_huffman, self.max_entries); @@ -496,12 +488,12 @@ impl QPackEncoder { } #[must_use] - pub fn local_stream_id(&self) -> Option { + pub const fn local_stream_id(&self) -> Option { self.local_stream.stream_id() } #[cfg(test)] - fn blocked_stream_cnt(&self) -> u16 { + const fn blocked_stream_cnt(&self) -> u16 { self.blocked_stream_cnt } } diff --git a/neqo-qpack/src/encoder_instructions.rs b/neqo-qpack/src/encoder_instructions.rs index 5564af969e..477904d112 100644 --- a/neqo-qpack/src/encoder_instructions.rs +++ b/neqo-qpack/src/encoder_instructions.rs @@ -122,7 +122,7 @@ impl ::std::fmt::Display for EncoderInstructionReader { } impl EncoderInstructionReader { - pub fn new() -> Self { + pub const fn new() -> Self { Self { state: EncoderInstructionReaderState::ReadInstruction, instruction: DecodedEncoderInstruction::NoInstruction, diff --git a/neqo-qpack/src/header_block.rs b/neqo-qpack/src/header_block.rs index 2e15bdf1fe..91811d9809 100644 --- a/neqo-qpack/src/header_block.rs +++ b/neqo-qpack/src/header_block.rs @@ -25,7 +25,7 @@ use crate::{ Error, Res, }; -#[derive(Default, Debug, PartialEq)] +#[derive(Default, Debug, PartialEq, Eq)] pub struct HeaderEncoder { buf: QpackData, base: u64, @@ -172,7 +172,7 @@ impl Deref for HeaderEncoder { } } -pub(crate) struct HeaderDecoder<'a> { +pub struct HeaderDecoder<'a> { buf: ReceiverBufferWrapper<'a>, base: u64, req_insert_cnt: u64, @@ -191,7 +191,7 @@ pub enum HeaderDecoderResult { } impl<'a> HeaderDecoder<'a> { - pub fn new(buf: &'a [u8]) -> Self { + pub const fn new(buf: &'a [u8]) -> Self { Self { buf: ReceiverBufferWrapper::new(buf), base: 0, @@ -278,7 +278,7 @@ impl<'a> HeaderDecoder<'a> { Ok(HeaderDecoderResult::Headers(h)) } - pub fn get_req_insert_cnt(&self) -> u64 { + pub const fn get_req_insert_cnt(&self) -> u64 { self.req_insert_cnt } diff --git a/neqo-qpack/src/huffman.rs b/neqo-qpack/src/huffman.rs index 30bb880438..869a53545e 100644 --- a/neqo-qpack/src/huffman.rs +++ b/neqo-qpack/src/huffman.rs @@ -17,7 +17,7 @@ struct BitReader<'a> { } impl<'a> BitReader<'a> { - pub fn new(input: &'a [u8]) -> Self { + pub const fn new(input: &'a [u8]) -> Self { BitReader { input, offset: 0, @@ -60,7 +60,7 @@ impl<'a> BitReader<'a> { } } - pub fn has_more_data(&self) -> bool { + pub const fn has_more_data(&self) -> bool { !self.input.is_empty() && (self.offset != self.input.len() || (self.current_bit != 0)) } } diff --git a/neqo-qpack/src/lib.rs b/neqo-qpack/src/lib.rs index 10ee5df61c..c8ef48f947 100644 --- a/neqo-qpack/src/lib.rs +++ b/neqo-qpack/src/lib.rs @@ -64,7 +64,7 @@ pub enum Error { impl Error { #[must_use] - pub fn code(&self) -> neqo_transport::AppError { + pub const fn code(&self) -> neqo_transport::AppError { match self { Self::DecompressionFailed => 0x200, Self::EncoderStream => 0x201, diff --git a/neqo-qpack/src/prefix.rs b/neqo-qpack/src/prefix.rs index 0085de0df9..7b2f4af79a 100644 --- a/neqo-qpack/src/prefix.rs +++ b/neqo-qpack/src/prefix.rs @@ -33,15 +33,15 @@ impl Prefix { } } - pub fn len(self) -> u8 { + pub const fn len(self) -> u8 { self.len } - pub fn prefix(self) -> u8 { + pub const fn prefix(self) -> u8 { self.prefix } - pub fn cmp_prefix(self, b: u8) -> bool { + pub const fn cmp_prefix(self, b: u8) -> bool { (b & self.mask) == self.prefix } } diff --git a/neqo-qpack/src/qlog.rs b/neqo-qpack/src/qlog.rs index 8d48efb0aa..a91b9875e2 100644 --- a/neqo-qpack/src/qlog.rs +++ b/neqo-qpack/src/qlog.rs @@ -12,11 +12,7 @@ use qlog::events::{ EventData, RawInfo, }; -pub fn qpack_read_insert_count_increment_instruction( - qlog: &mut NeqoQlog, - increment: u64, - data: &[u8], -) { +pub fn qpack_read_insert_count_increment_instruction(qlog: &NeqoQlog, increment: u64, data: &[u8]) { qlog.add_event_data(|| { let raw = RawInfo { length: Some(8), diff --git a/neqo-qpack/src/qpack_send_buf.rs b/neqo-qpack/src/qpack_send_buf.rs index c0b8d7af1b..fdf5047ab6 100644 --- a/neqo-qpack/src/qpack_send_buf.rs +++ b/neqo-qpack/src/qpack_send_buf.rs @@ -10,8 +10,8 @@ use neqo_common::Encoder; use crate::{huffman::encode_huffman, prefix::Prefix}; -#[derive(Default, Debug, PartialEq)] -pub(crate) struct QpackData { +#[derive(Default, Debug, PartialEq, Eq)] +pub struct QpackData { buf: Vec, } diff --git a/neqo-qpack/src/reader.rs b/neqo-qpack/src/reader.rs index 8afedddd76..c408b3d62c 100644 --- a/neqo-qpack/src/reader.rs +++ b/neqo-qpack/src/reader.rs @@ -79,11 +79,11 @@ impl<'a> ReadByte for ReceiverBufferWrapper<'a> { } impl<'a> ReceiverBufferWrapper<'a> { - pub fn new(buf: &'a [u8]) -> Self { + pub const fn new(buf: &'a [u8]) -> Self { Self { buf, offset: 0 } } - pub fn peek(&self) -> Res { + pub const fn peek(&self) -> Res { if self.offset == self.buf.len() { Err(Error::DecompressionFailed) } else { @@ -91,7 +91,7 @@ impl<'a> ReceiverBufferWrapper<'a> { } } - pub fn done(&self) -> bool { + pub const fn done(&self) -> bool { self.offset == self.buf.len() } diff --git a/neqo-qpack/src/static_table.rs b/neqo-qpack/src/static_table.rs index 4407fbce59..79af223f57 100644 --- a/neqo-qpack/src/static_table.rs +++ b/neqo-qpack/src/static_table.rs @@ -12,15 +12,15 @@ pub struct StaticTableEntry { } impl StaticTableEntry { - pub fn name(&self) -> &[u8] { + pub const fn name(&self) -> &[u8] { self.name } - pub fn value(&self) -> &[u8] { + pub const fn value(&self) -> &[u8] { self.value } - pub fn index(&self) -> u64 { + pub const fn index(&self) -> u64 { self.index } } diff --git a/neqo-qpack/src/table.rs b/neqo-qpack/src/table.rs index d5275ec98f..ea6ae58d35 100644 --- a/neqo-qpack/src/table.rs +++ b/neqo-qpack/src/table.rs @@ -22,7 +22,7 @@ pub struct LookupResult { } #[derive(Debug)] -pub(crate) struct DynamicTableEntry { +pub struct DynamicTableEntry { base: u64, name: Vec, value: Vec, @@ -32,7 +32,7 @@ pub(crate) struct DynamicTableEntry { } impl DynamicTableEntry { - pub fn can_reduce(&self, first_not_acked: u64) -> bool { + pub const fn can_reduce(&self, first_not_acked: u64) -> bool { self.refs == 0 && self.base < first_not_acked } @@ -57,13 +57,13 @@ impl DynamicTableEntry { &self.value } - pub fn index(&self) -> u64 { + pub const fn index(&self) -> u64 { self.base } } #[derive(Debug)] -pub(crate) struct HeaderTable { +pub struct HeaderTable { dynamic: VecDeque, /// The total capacity (in QPACK bytes) of the table. This is set by /// configuration. @@ -88,7 +88,7 @@ impl ::std::fmt::Display for HeaderTable { } impl HeaderTable { - pub fn new(encoder: bool) -> Self { + pub const fn new(encoder: bool) -> Self { Self { dynamic: VecDeque::new(), capacity: 0, @@ -99,12 +99,12 @@ impl HeaderTable { } /// Returns number of inserts. - pub fn base(&self) -> u64 { + pub const fn base(&self) -> u64 { self.base } /// Returns capacity of the dynamic table - pub fn capacity(&self) -> u64 { + pub const fn capacity(&self) -> u64 { self.capacity } @@ -340,7 +340,7 @@ impl HeaderTable { value ); let name = if name_static_table { - HeaderTable::get_static(name_index)?.name().to_vec() + Self::get_static(name_index)?.name().to_vec() } else { self.get_dynamic(name_index, self.base, false)? .name() @@ -385,7 +385,7 @@ impl HeaderTable { } /// Return number of acknowledge inserts. - pub fn get_acked_inserts_cnt(&self) -> u64 { + pub const fn get_acked_inserts_cnt(&self) -> u64 { self.acked_inserts_cnt } } diff --git a/neqo-transport/Cargo.toml b/neqo-transport/Cargo.toml index 2abdbbfd95..c72df5e7f1 100644 --- a/neqo-transport/Cargo.toml +++ b/neqo-transport/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/neqo-transport/src/ackrate.rs b/neqo-transport/src/ackrate.rs index d5923805d9..bad69d0a9b 100644 --- a/neqo-transport/src/ackrate.rs +++ b/neqo-transport/src/ackrate.rs @@ -146,7 +146,7 @@ pub enum PeerAckDelay { } impl PeerAckDelay { - pub fn fixed(max_ack_delay: Duration) -> Self { + pub const fn fixed(max_ack_delay: Duration) -> Self { Self::Fixed(max_ack_delay) } diff --git a/neqo-transport/src/addr_valid.rs b/neqo-transport/src/addr_valid.rs index f596cfc3cb..1ea574de4a 100644 --- a/neqo-transport/src/addr_valid.rs +++ b/neqo-transport/src/addr_valid.rs @@ -222,6 +222,7 @@ impl AddressValidation { let enc = &token[TOKEN_IDENTIFIER_RETRY.len()..]; // Note that this allows the token identifier part to be corrupted. // That's OK here as we don't depend on that being authenticated. + #[allow(clippy::option_if_let_else)] if let Some(cid) = self.decrypt_token(enc, peer_address, retry, now) { if retry { // This is from Retry, so we should have an ODCID >= 8. @@ -304,15 +305,13 @@ impl NewTokenState { ref mut old, } = self { - if let Some(t) = pending.pop() { + pending.pop().map(|t| { if old.len() >= MAX_SAVED_TOKENS { old.remove(0); } old.push(t); - Some(&old[old.len() - 1]) - } else { - None - } + old[old.len() - 1].as_slice() + }) } else { unreachable!(); } diff --git a/neqo-transport/src/cc/classic_cc.rs b/neqo-transport/src/cc/classic_cc.rs index 23f0d04bd2..d825fd28b1 100644 --- a/neqo-transport/src/cc/classic_cc.rs +++ b/neqo-transport/src/cc/classic_cc.rs @@ -50,7 +50,7 @@ enum State { } impl State { - pub fn in_recovery(self) -> bool { + pub const fn in_recovery(self) -> bool { matches!(self, Self::RecoveryStart | Self::Recovery) } @@ -59,7 +59,7 @@ impl State { } /// These states are transient, we tell qlog on entry, but not on exit. - pub fn transient(self) -> bool { + pub const fn transient(self) -> bool { matches!(self, Self::RecoveryStart | Self::PersistentCongestion) } @@ -72,7 +72,7 @@ impl State { }; } - pub fn to_qlog(self) -> &'static str { + pub const fn to_qlog(self) -> &'static str { match self { Self::SlowStart | Self::PersistentCongestion => "slow_start", Self::CongestionAvoidance => "congestion_avoidance", @@ -191,7 +191,7 @@ impl CongestionControl for ClassicCongestionControl { if self.state.in_recovery() { self.set_state(State::CongestionAvoidance); - qlog::metrics_updated(&mut self.qlog, &[QlogMetric::InRecovery(false)]); + qlog::metrics_updated(&self.qlog, &[QlogMetric::InRecovery(false)]); } new_acked += pkt.len(); @@ -244,7 +244,7 @@ impl CongestionControl for ClassicCongestionControl { self.acked_bytes = min(bytes_for_increase, self.acked_bytes); } qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[ QlogMetric::CongestionWindow(self.congestion_window), QlogMetric::BytesInFlight(self.bytes_in_flight), @@ -277,7 +277,7 @@ impl CongestionControl for ClassicCongestionControl { self.bytes_in_flight = self.bytes_in_flight.saturating_sub(pkt.len()); } qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[QlogMetric::BytesInFlight(self.bytes_in_flight)], ); @@ -311,7 +311,7 @@ impl CongestionControl for ClassicCongestionControl { assert!(self.bytes_in_flight >= pkt.len()); self.bytes_in_flight -= pkt.len(); qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[QlogMetric::BytesInFlight(self.bytes_in_flight)], ); qtrace!([self], "Ignore pkt with size {}", pkt.len()); @@ -321,7 +321,7 @@ impl CongestionControl for ClassicCongestionControl { fn discard_in_flight(&mut self) { self.bytes_in_flight = 0; qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[QlogMetric::BytesInFlight(self.bytes_in_flight)], ); } @@ -352,7 +352,7 @@ impl CongestionControl for ClassicCongestionControl { pkt.len() ); qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[QlogMetric::BytesInFlight(self.bytes_in_flight)], ); } @@ -380,7 +380,7 @@ impl ClassicCongestionControl { #[cfg(test)] #[must_use] - pub fn ssthresh(&self) -> usize { + pub const fn ssthresh(&self) -> usize { self.ssthresh } @@ -400,7 +400,7 @@ impl ClassicCongestionControl { } #[cfg(test)] - pub fn acked_bytes(&self) -> usize { + pub const fn acked_bytes(&self) -> usize { self.acked_bytes } @@ -470,7 +470,7 @@ impl ClassicCongestionControl { self.acked_bytes = 0; self.set_state(State::PersistentCongestion); qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[QlogMetric::CongestionWindow(self.congestion_window)], ); return true; @@ -483,7 +483,7 @@ impl ClassicCongestionControl { } #[must_use] - fn after_recovery_start(&mut self, packet: &SentPacket) -> bool { + fn after_recovery_start(&self, packet: &SentPacket) -> bool { // At the start of the recovery period, the state is transient and // all packets will have been sent before recovery. When sending out // the first packet we transition to the non-transient `Recovery` @@ -515,7 +515,7 @@ impl ClassicCongestionControl { self.ssthresh ); qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[ QlogMetric::CongestionWindow(self.congestion_window), QlogMetric::SsThresh(self.ssthresh), diff --git a/neqo-transport/src/cc/cubic.rs b/neqo-transport/src/cc/cubic.rs index 058a4c2aa4..d7ac1068f7 100644 --- a/neqo-transport/src/cc/cubic.rs +++ b/neqo-transport/src/cc/cubic.rs @@ -98,7 +98,7 @@ impl Cubic { /// W_cubic(t) = C*(t-K)^3 + W_max (Eq. 1) /// t is relative to the start of the congestion avoidance phase and it is in seconds. fn w_cubic(&self, t: f64) -> f64 { - CUBIC_C * (t - self.k).powi(3) * MAX_DATAGRAM_SIZE_F64 + self.w_max + (CUBIC_C * (t - self.k).powi(3)).mul_add(MAX_DATAGRAM_SIZE_F64, self.w_max) } fn start_epoch(&mut self, curr_cwnd_f64: f64, new_acked_f64: f64, now: Instant) { @@ -152,9 +152,10 @@ impl WindowAdjustment for Cubic { let target_cubic = self.w_cubic(time_ca); let tcp_cnt = self.estimated_tcp_cwnd / CUBIC_ALPHA; - while self.tcp_acked_bytes > tcp_cnt { - self.tcp_acked_bytes -= tcp_cnt; - self.estimated_tcp_cwnd += MAX_DATAGRAM_SIZE_F64; + let incr = (self.tcp_acked_bytes / tcp_cnt).floor(); + if incr > 0.0 { + self.tcp_acked_bytes -= incr * tcp_cnt; + self.estimated_tcp_cwnd += incr * MAX_DATAGRAM_SIZE_F64; } let target_cwnd = target_cubic.max(self.estimated_tcp_cwnd); diff --git a/neqo-transport/src/cc/tests/cubic.rs b/neqo-transport/src/cc/tests/cubic.rs index 4d8c436cc4..9c9cec17cf 100644 --- a/neqo-transport/src/cc/tests/cubic.rs +++ b/neqo-transport/src/cc/tests/cubic.rs @@ -174,19 +174,19 @@ fn tcp_phase() { assert!(num_acks2 < expected_ack_tcp_increase2); // The time needed to increase cwnd by MAX_DATAGRAM_SIZE using the cubic equation will be - // calculates from: W_cubic(elapsed_time + t_to_increase) - W_cubis(elapsed_time) = + // calculates from: W_cubic(elapsed_time + t_to_increase) - W_cubic(elapsed_time) = // MAX_DATAGRAM_SIZE => CUBIC_C * (elapsed_time + t_to_increase)^3 * MAX_DATAGRAM_SIZE + - // CWND_INITIAL - CUBIC_C * elapsed_time^3 * MAX_DATAGRAM_SIZE + CWND_INITIAL = + // CWND_INITIAL - CUBIC_C * elapsed_time^3 * MAX_DATAGRAM_SIZE + CWND_INITIAL = // MAX_DATAGRAM_SIZE => t_to_increase = cbrt((1 + CUBIC_C * elapsed_time^3) / CUBIC_C) - // elapsed_time (t_to_increase is in seconds) // number of ack needed is t_to_increase / time_increase. let expected_ack_cubic_increase = - ((((1.0 + CUBIC_C * (elapsed_time).as_secs_f64().powi(3)) / CUBIC_C).cbrt() + (((CUBIC_C.mul_add((elapsed_time).as_secs_f64().powi(3), 1.0) / CUBIC_C).cbrt() - elapsed_time.as_secs_f64()) / time_increase.as_secs_f64()) .ceil() as u64; // num_acks is very close to the calculated value. The exact value is hard to calculate - // because the proportional increase(i.e. curr_cwnd_f64 / (target - curr_cwnd_f64) * + // because the proportional increase (i.e. curr_cwnd_f64 / (target - curr_cwnd_f64) * // MAX_DATAGRAM_SIZE_F64) and the byte counting. assert_eq!(num_acks2, expected_ack_cubic_increase + 2); } @@ -222,10 +222,9 @@ fn cubic_phase() { next_pn_send = fill_cwnd(&mut cubic, next_pn_send, now); } - let expected = - (CUBIC_C * ((now - epoch_start).as_secs_f64() - k).powi(3) * MAX_DATAGRAM_SIZE_F64 - + CWND_INITIAL_10_F64) - .round() as usize; + let expected = (CUBIC_C * ((now - epoch_start).as_secs_f64() - k).powi(3)) + .mul_add(MAX_DATAGRAM_SIZE_F64, CWND_INITIAL_10_F64) + .round() as usize; assert_within(cubic.cwnd(), expected, MAX_DATAGRAM_SIZE); } diff --git a/neqo-transport/src/cid.rs b/neqo-transport/src/cid.rs index 6b3a95eaf0..767b5242ad 100644 --- a/neqo-transport/src/cid.rs +++ b/neqo-transport/src/cid.rs @@ -210,7 +210,7 @@ pub struct RandomConnectionIdGenerator { impl RandomConnectionIdGenerator { #[must_use] - pub fn new(len: usize) -> Self { + pub const fn new(len: usize) -> Self { Self { len } } } @@ -294,7 +294,7 @@ impl ConnectionIdEntry<[u8; 16]> { } /// The sequence number of this entry. - pub fn sequence_number(&self) -> u64 { + pub const fn sequence_number(&self) -> u64 { self.seqno } @@ -318,13 +318,13 @@ impl ConnectionIdEntry<[u8; 16]> { impl ConnectionIdEntry<()> { /// Create an initial entry. - pub fn initial_local(cid: ConnectionId) -> Self { + pub const fn initial_local(cid: ConnectionId) -> Self { Self::new(0, cid, ()) } } impl ConnectionIdEntry { - pub fn new(seqno: u64, cid: ConnectionId, srt: SRT) -> Self { + pub const fn new(seqno: u64, cid: ConnectionId, srt: SRT) -> Self { Self { seqno, cid, srt } } @@ -340,11 +340,11 @@ impl ConnectionIdEntry { self.cid = cid; } - pub fn connection_id(&self) -> &ConnectionId { + pub const fn connection_id(&self) -> &ConnectionId { &self.cid } - pub fn reset_token(&self) -> &SRT { + pub const fn reset_token(&self) -> &SRT { &self.srt } } diff --git a/neqo-transport/src/connection/idle.rs b/neqo-transport/src/connection/idle.rs index 9fdc1482fc..5aaf1cb4d7 100644 --- a/neqo-transport/src/connection/idle.rs +++ b/neqo-transport/src/connection/idle.rs @@ -32,7 +32,7 @@ pub struct IdleTimeout { } impl IdleTimeout { - pub fn new(timeout: Duration) -> Self { + pub const fn new(timeout: Duration) -> Self { Self { timeout, state: IdleTimeoutState::Init, @@ -46,7 +46,7 @@ impl IdleTimeout { self.timeout = min(self.timeout, peer_timeout); } - fn start(&self, now: Instant) -> Instant { + const fn start(&self, now: Instant) -> Instant { match self.state { IdleTimeoutState::Init => now, IdleTimeoutState::PacketReceived(t) | IdleTimeoutState::AckElicitingPacketSent(t) => t, diff --git a/neqo-transport/src/connection/mod.rs b/neqo-transport/src/connection/mod.rs index 3aa6ce8304..2ff2f7cc26 100644 --- a/neqo-transport/src/connection/mod.rs +++ b/neqo-transport/src/connection/mod.rs @@ -121,7 +121,7 @@ impl Output { /// Get a reference to the Datagram, if any. #[must_use] - pub fn as_dgram_ref(&self) -> Option<&Datagram> { + pub const fn as_dgram_ref(&self) -> Option<&Datagram> { match self { Self::Datagram(dg) => Some(dg), _ => None, @@ -130,7 +130,7 @@ impl Output { /// Ask how long the caller should wait before calling back. #[must_use] - pub fn callback(&self) -> Duration { + pub const fn callback(&self) -> Duration { match self { Self::Callback(t) => *t, _ => Duration::new(0, 0), @@ -199,22 +199,14 @@ impl AddressValidationInfo { } } - pub fn generate_new_token( - &mut self, - peer_address: SocketAddr, - now: Instant, - ) -> Option> { + pub fn generate_new_token(&self, peer_address: SocketAddr, now: Instant) -> Option> { match self { - Self::Server(ref w) => { - if let Some(validation) = w.upgrade() { - validation - .borrow() - .generate_new_token(peer_address, now) - .ok() - } else { - None - } - } + Self::Server(ref w) => w.upgrade().and_then(|validation| { + validation + .borrow() + .generate_new_token(peer_address, now) + .ok() + }), Self::None => None, _ => unreachable!("called a server function on a client"), } @@ -492,7 +484,7 @@ impl Connection { /// will always be present for `Role::Client` but not if `Role::Server` is in /// `State::Init`. #[must_use] - pub fn odcid(&self) -> Option<&ConnectionId> { + pub const fn odcid(&self) -> Option<&ConnectionId> { self.original_destination_cid.as_ref() } @@ -851,25 +843,25 @@ impl Connection { /// Get the role of the connection. #[must_use] - pub fn role(&self) -> Role { + pub const fn role(&self) -> Role { self.role } /// Get the state of the connection. #[must_use] - pub fn state(&self) -> &State { + pub const fn state(&self) -> &State { &self.state } /// The QUIC version in use. #[must_use] - pub fn version(&self) -> Version { + pub const fn version(&self) -> Version { self.version } /// Get the 0-RTT state of the connection. #[must_use] - pub fn zero_rtt_state(&self) -> ZeroRttState { + pub const fn zero_rtt_state(&self) -> ZeroRttState { self.zero_rtt_state } @@ -982,7 +974,7 @@ impl Connection { if let Some(path) = self.paths.primary() { let lost = self.loss_recovery.timeout(&path, now); self.handle_lost_packets(&lost); - qlog::packets_lost(&mut self.qlog, &lost); + qlog::packets_lost(&self.qlog, &lost); } if self.release_resumption_token_timer.is_some() { @@ -1280,7 +1272,7 @@ impl Connection { .set_initial(self.conn_params.get_versions().initial()); mem::swap(self, &mut c); qlog::client_version_information_negotiated( - &mut self.qlog, + &self.qlog, self.conn_params.get_versions().all(), supported, version, @@ -1541,7 +1533,7 @@ impl Connection { neqo_common::write_item_to_fuzzing_corpus(target, &payload[..]); } - qlog::packet_received(&mut self.qlog, &packet, &payload); + qlog::packet_received(&self.qlog, &packet, &payload); let space = PacketNumberSpace::from(payload.packet_type()); if self.acks.get_mut(space).unwrap().is_duplicate(payload.pn()) { qdebug!([self], "Duplicate packet {}-{}", space, payload.pn()); @@ -1582,7 +1574,7 @@ impl Connection { // the rest of the datagram on the floor, but don't generate an error. self.check_stateless_reset(path, d, dcid.is_none(), now)?; self.stats.borrow_mut().pkt_dropped("Decryption failure"); - qlog::packet_dropped(&mut self.qlog, &packet); + qlog::packet_dropped(&self.qlog, &packet); } } slc = remainder; @@ -1890,31 +1882,31 @@ impl Connection { | State::WaitVersion | State::Handshaking | State::Connected - | State::Confirmed => { - if let Some(path) = self.paths.select_path() { + | State::Confirmed => self.paths.select_path().map_or_else( + || Ok(SendOption::default()), + |path| { let res = self.output_path(&path, now, &None); self.capture_error(Some(path), now, 0, res) - } else { - Ok(SendOption::default()) - } - } + }, + ), State::Closing { .. } | State::Draining { .. } | State::Closed(_) => { - if let Some(details) = self.state_signaling.close_frame() { - let path = Rc::clone(details.path()); - // In some error cases, we will not be able to make a new, permanent path. - // For example, if we run out of connection IDs and the error results from - // a packet on a new path, we avoid sending (and the privacy risk) rather - // than reuse a connection ID. - let res = if path.borrow().is_temporary() { - assert!(!cfg!(test), "attempting to close with a temporary path"); - Err(Error::InternalError) - } else { - self.output_path(&path, now, &Some(details)) - }; - self.capture_error(Some(path), now, 0, res) - } else { - Ok(SendOption::default()) - } + self.state_signaling.close_frame().map_or_else( + || Ok(SendOption::default()), + |details| { + let path = Rc::clone(details.path()); + // In some error cases, we will not be able to make a new, permanent path. + // For example, if we run out of connection IDs and the error results from + // a packet on a new path, we avoid sending (and the privacy risk) rather + // than reuse a connection ID. + let res = if path.borrow().is_temporary() { + assert!(!cfg!(test), "attempting to close with a temporary path"); + Err(Error::InternalError) + } else { + self.output_path(&path, now, &Some(details)) + }; + self.capture_error(Some(path), now, 0, res) + }, + ) } }; res.unwrap_or_default() @@ -1961,12 +1953,7 @@ impl Connection { ) -> PacketNumber { // Get the packet number and work out how long it is. let pn = tx.next_pn(); - let unacked_range = if let Some(la) = largest_acknowledged { - // Double the range from this to the last acknowledged in this space. - (pn - la) << 1 - } else { - pn + 1 - }; + let unacked_range = largest_acknowledged.map_or_else(|| pn + 1, |la| (pn - la) << 1); // Count how many bytes in this range are non-zero. let pn_len = mem::size_of::() - usize::try_from(unacked_range.leading_zeros() / 8).unwrap(); @@ -2313,7 +2300,7 @@ impl Connection { path.borrow().tos(), ); qlog::packet_sent( - &mut self.qlog, + &self.qlog, pt, pn, builder.len() - header_start + aead_expansion, @@ -2413,9 +2400,9 @@ impl Connection { qdebug!([self], "client_start"); debug_assert_eq!(self.role, Role::Client); if let Some(path) = self.paths.primary() { - qlog::client_connection_started(&mut self.qlog, &path); + qlog::client_connection_started(&self.qlog, &path); } - qlog::client_version_information_initiated(&mut self.qlog, self.conn_params.get_versions()); + qlog::client_version_information_initiated(&self.qlog, self.conn_params.get_versions()); self.handshake(now, self.version, PacketNumberSpace::Initial, None)?; self.set_state(State::WaitInitial); @@ -2487,14 +2474,11 @@ impl Connection { return Err(Error::TransportParameterError); } - let reset_token = if let Some(token) = remote.get_bytes(tparams::STATELESS_RESET_TOKEN) - { - <[u8; 16]>::try_from(token).unwrap() - } else { - // The other side didn't provide a stateless reset token. - // That's OK, they can try guessing this. - ConnectionIdEntry::random_srt() - }; + let reset_token = remote + .get_bytes(tparams::STATELESS_RESET_TOKEN) + .map_or_else(ConnectionIdEntry::random_srt, |token| { + <[u8; 16]>::try_from(token).unwrap() + }); let path = self.paths.primary().ok_or(Error::NoAvailablePath)?; path.borrow_mut().set_reset_token(reset_token); @@ -2515,11 +2499,11 @@ impl Connection { self.cid_manager.set_limit(max_active_cids); } self.set_initial_limits(); - qlog::connection_tparams_set(&mut self.qlog, &self.tps.borrow()); + qlog::connection_tparams_set(&self.qlog, &self.tps.borrow()); Ok(()) } - fn validate_cids(&mut self) -> Res<()> { + fn validate_cids(&self) -> Res<()> { let tph = self.tps.borrow(); let remote_tps = tph.remote.as_ref().unwrap(); @@ -2580,7 +2564,7 @@ impl Connection { } /// Validate the `version_negotiation` transport parameter from the peer. - fn validate_versions(&mut self) -> Res<()> { + fn validate_versions(&self) -> Res<()> { let tph = self.tps.borrow(); let remote_tps = tph.remote.as_ref().unwrap(); // `current` and `other` are the value from the peer's transport parameters. @@ -2926,12 +2910,13 @@ impl Connection { fn decode_ack_delay(&self, v: u64) -> Duration { // If we have remote transport parameters, use them. // Otherwise, ack delay should be zero (because it's the handshake). - if let Some(r) = self.tps.borrow().remote.as_ref() { - let exponent = u32::try_from(r.get_integer(tparams::ACK_DELAY_EXPONENT)).unwrap(); - Duration::from_micros(v.checked_shl(exponent).unwrap_or(u64::MAX)) - } else { - Duration::new(0, 0) - } + self.tps.borrow().remote.as_ref().map_or_else( + || Duration::new(0, 0), + |r| { + let exponent = u32::try_from(r.get_integer(tparams::ACK_DELAY_EXPONENT)).unwrap(); + Duration::from_micros(v.checked_shl(exponent).unwrap_or(u64::MAX)) + }, + ) } fn handle_ack( @@ -2980,7 +2965,7 @@ impl Connection { } } self.handle_lost_packets(&lost_packets); - qlog::packets_lost(&mut self.qlog, &lost_packets); + qlog::packets_lost(&self.qlog, &lost_packets); let stats = &mut self.stats.borrow_mut().frame_rx; stats.ack += 1; stats.largest_acknowledged = max(stats.largest_acknowledged, largest_acknowledged); @@ -3019,7 +3004,7 @@ impl Connection { let path = self.paths.primary().ok_or(Error::NoAvailablePath)?; path.borrow_mut().set_valid(now); // Generate a qlog event that the server connection started. - qlog::server_connection_started(&mut self.qlog, &path); + qlog::server_connection_started(&self.qlog, &path); } else { self.zero_rtt_state = if self.crypto.tls.info().unwrap().early_data_accepted() { ZeroRttState::AcceptedClient @@ -3055,7 +3040,7 @@ impl Connection { self.streams.clear_streams(); } self.events.connection_state_change(state); - qlog::connection_state_updated(&mut self.qlog, &self.state); + qlog::connection_state_updated(&self.qlog, &self.state); } else if mem::discriminant(&state) != mem::discriminant(&self.state) { // Only tolerate a regression in state if the new state is closing // and the connection is already closed. @@ -3287,7 +3272,7 @@ impl Connection { } #[must_use] - pub fn remote_datagram_size(&self) -> u64 { + pub const fn remote_datagram_size(&self) -> u64 { self.quic_datagrams.remote_datagram_size() } diff --git a/neqo-transport/src/connection/params.rs b/neqo-transport/src/connection/params.rs index d8aa617024..3263e3b734 100644 --- a/neqo-transport/src/connection/params.rs +++ b/neqo-transport/src/connection/params.rs @@ -107,7 +107,7 @@ impl Default for ConnectionParameters { impl ConnectionParameters { #[must_use] - pub fn get_versions(&self) -> &VersionConfig { + pub const fn get_versions(&self) -> &VersionConfig { &self.versions } @@ -126,29 +126,29 @@ impl ConnectionParameters { } #[must_use] - pub fn get_cc_algorithm(&self) -> CongestionControlAlgorithm { + pub const fn get_cc_algorithm(&self) -> CongestionControlAlgorithm { self.cc_algorithm } #[must_use] - pub fn cc_algorithm(mut self, v: CongestionControlAlgorithm) -> Self { + pub const fn cc_algorithm(mut self, v: CongestionControlAlgorithm) -> Self { self.cc_algorithm = v; self } #[must_use] - pub fn get_max_data(&self) -> u64 { + pub const fn get_max_data(&self) -> u64 { self.max_data } #[must_use] - pub fn max_data(mut self, v: u64) -> Self { + pub const fn max_data(mut self, v: u64) -> Self { self.max_data = v; self } #[must_use] - pub fn get_max_streams(&self, stream_type: StreamType) -> u64 { + pub const fn get_max_streams(&self, stream_type: StreamType) -> u64 { match stream_type { StreamType::BiDi => self.max_streams_bidi, StreamType::UniDi => self.max_streams_uni, @@ -217,31 +217,31 @@ impl ConnectionParameters { /// Set a preferred address (which only has an effect for a server). #[must_use] - pub fn preferred_address(mut self, preferred: PreferredAddress) -> Self { + pub const fn preferred_address(mut self, preferred: PreferredAddress) -> Self { self.preferred_address = PreferredAddressConfig::Address(preferred); self } /// Disable the use of preferred addresses. #[must_use] - pub fn disable_preferred_address(mut self) -> Self { + pub const fn disable_preferred_address(mut self) -> Self { self.preferred_address = PreferredAddressConfig::Disabled; self } #[must_use] - pub fn get_preferred_address(&self) -> &PreferredAddressConfig { + pub const fn get_preferred_address(&self) -> &PreferredAddressConfig { &self.preferred_address } #[must_use] - pub fn ack_ratio(mut self, ack_ratio: u8) -> Self { + pub const fn ack_ratio(mut self, ack_ratio: u8) -> Self { self.ack_ratio = ack_ratio; self } #[must_use] - pub fn get_ack_ratio(&self) -> u8 { + pub const fn get_ack_ratio(&self) -> u8 { self.ack_ratio } @@ -256,23 +256,23 @@ impl ConnectionParameters { } #[must_use] - pub fn get_idle_timeout(&self) -> Duration { + pub const fn get_idle_timeout(&self) -> Duration { self.idle_timeout } #[must_use] - pub fn get_datagram_size(&self) -> u64 { + pub const fn get_datagram_size(&self) -> u64 { self.datagram_size } #[must_use] - pub fn datagram_size(mut self, v: u64) -> Self { + pub const fn datagram_size(mut self, v: u64) -> Self { self.datagram_size = v; self } #[must_use] - pub fn get_outgoing_datagram_queue(&self) -> usize { + pub const fn get_outgoing_datagram_queue(&self) -> usize { self.outgoing_datagram_queue } @@ -284,7 +284,7 @@ impl ConnectionParameters { } #[must_use] - pub fn get_incoming_datagram_queue(&self) -> usize { + pub const fn get_incoming_datagram_queue(&self) -> usize { self.incoming_datagram_queue } @@ -296,7 +296,7 @@ impl ConnectionParameters { } #[must_use] - pub fn get_fast_pto(&self) -> u8 { + pub const fn get_fast_pto(&self) -> u8 { self.fast_pto } @@ -323,23 +323,23 @@ impl ConnectionParameters { } #[must_use] - pub fn is_greasing(&self) -> bool { + pub const fn is_greasing(&self) -> bool { self.grease } #[must_use] - pub fn grease(mut self, grease: bool) -> Self { + pub const fn grease(mut self, grease: bool) -> Self { self.grease = grease; self } #[must_use] - pub fn pacing_enabled(&self) -> bool { + pub const fn pacing_enabled(&self) -> bool { self.pacing } #[must_use] - pub fn pacing(mut self, pacing: bool) -> Self { + pub const fn pacing(mut self, pacing: bool) -> Self { self.pacing = pacing; self } diff --git a/neqo-transport/src/connection/saved.rs b/neqo-transport/src/connection/saved.rs index f5616c732a..d5e0313e52 100644 --- a/neqo-transport/src/connection/saved.rs +++ b/neqo-transport/src/connection/saved.rs @@ -56,7 +56,7 @@ impl SavedDatagrams { } } - pub fn available(&self) -> Option { + pub const fn available(&self) -> Option { self.available } diff --git a/neqo-transport/src/connection/state.rs b/neqo-transport/src/connection/state.rs index e76f937938..ddb7d81a11 100644 --- a/neqo-transport/src/connection/state.rs +++ b/neqo-transport/src/connection/state.rs @@ -54,12 +54,12 @@ pub enum State { impl State { #[must_use] - pub fn connected(&self) -> bool { + pub const fn connected(&self) -> bool { matches!(self, Self::Connected | Self::Confirmed) } #[must_use] - pub fn closed(&self) -> bool { + pub const fn closed(&self) -> bool { matches!( self, Self::Closing { .. } | Self::Draining { .. } | Self::Closed(_) @@ -67,7 +67,7 @@ impl State { } #[must_use] - pub fn error(&self) -> Option<&CloseReason> { + pub const fn error(&self) -> Option<&CloseReason> { if let Self::Closing { error, .. } | Self::Draining { error, .. } | Self::Closed(error) = self { @@ -137,7 +137,7 @@ impl ClosingFrame { } } - pub fn path(&self) -> &PathRef { + pub const fn path(&self) -> &PathRef { &self.path } @@ -162,7 +162,7 @@ impl ClosingFrame { pub const MIN_LENGTH: usize = 1 + 8 + 8 + 2 + 8; pub fn write_frame(&self, builder: &mut PacketBuilder) { - if builder.remaining() < ClosingFrame::MIN_LENGTH { + if builder.remaining() < Self::MIN_LENGTH { return; } match &self.error { diff --git a/neqo-transport/src/connection/tests/handshake.rs b/neqo-transport/src/connection/tests/handshake.rs index 4cab1696e7..0165fa70eb 100644 --- a/neqo-transport/src/connection/tests/handshake.rs +++ b/neqo-transport/src/connection/tests/handshake.rs @@ -1169,7 +1169,7 @@ fn emit_authentication_needed_once() { // packet, but be large enough that the CertificateVerify message does not // also fit in the same packet. Our default test setup achieves this, but // changes to the setup might invalidate this test. - let _ = client.process(server1.as_dgram_ref(), now()); + _ = client.process(server1.as_dgram_ref(), now()); assert_eq!(1, authentication_needed_count(&mut client)); assert!(client.peer_certificate().is_some()); @@ -1177,6 +1177,6 @@ fn emit_authentication_needed_once() { // `Connection::authenticated`. On receiving the second packet from the // server, the client must not emit a another // `ConnectionEvent::AuthenticationNeeded`. - let _ = client.process(server2.as_dgram_ref(), now()); + _ = client.process(server2.as_dgram_ref(), now()); assert_eq!(0, authentication_needed_count(&mut client)); } diff --git a/neqo-transport/src/connection/tests/migration.rs b/neqo-transport/src/connection/tests/migration.rs index 2304917246..17f3e549fa 100644 --- a/neqo-transport/src/connection/tests/migration.rs +++ b/neqo-transport/src/connection/tests/migration.rs @@ -56,7 +56,7 @@ fn change_path(d: &Datagram, a: SocketAddr) -> Datagram { Datagram::new(a, a, d.tos(), &d[..]) } -fn new_port(a: SocketAddr) -> SocketAddr { +const fn new_port(a: SocketAddr) -> SocketAddr { let (port, _) = a.port().overflowing_add(410); SocketAddr::new(a.ip(), port) } diff --git a/neqo-transport/src/connection/tests/mod.rs b/neqo-transport/src/connection/tests/mod.rs index 65283b8eb8..2fb70881b1 100644 --- a/neqo-transport/src/connection/tests/mod.rs +++ b/neqo-transport/src/connection/tests/mod.rs @@ -549,7 +549,7 @@ const fn cwnd_packets(data: usize) -> usize { /// Determine the size of the last packet. /// The minimal size of a packet is `ACK_ONLY_SIZE_LIMIT`. -fn last_packet(cwnd: usize) -> usize { +const fn last_packet(cwnd: usize) -> usize { if (cwnd % PATH_MTU_V6) > ACK_ONLY_SIZE_LIMIT { cwnd % PATH_MTU_V6 } else { diff --git a/neqo-transport/src/crypto.rs b/neqo-transport/src/crypto.rs index aca76b8bb9..a9a76ec916 100644 --- a/neqo-transport/src/crypto.rs +++ b/neqo-transport/src/crypto.rs @@ -42,7 +42,7 @@ const MAX_AUTH_TAG: usize = 32; /// to update keys. This has to be much smaller than the number returned /// by `CryptoDxState::limit` or updates will happen too often. As we don't /// need to ask permission to update, this can be quite small. -pub(crate) const UPDATE_WRITE_KEYS_AT: PacketNumber = 100; +pub const UPDATE_WRITE_KEYS_AT: PacketNumber = 100; // This is a testing kludge that allows for overwriting the number of // invocations of the next cipher to operate. With this, it is possible @@ -50,7 +50,7 @@ pub(crate) const UPDATE_WRITE_KEYS_AT: PacketNumber = 100; // when it hits `UPDATE_WRITE_KEYS_AT` and an automatic update should occur. // This is a little crude, but it saves a lot of plumbing. #[cfg(test)] -thread_local!(pub(crate) static OVERWRITE_INVOCATIONS: RefCell> = RefCell::default()); +thread_local!(pub static OVERWRITE_INVOCATIONS: RefCell> = RefCell::default()); #[derive(Debug)] pub struct Crypto { @@ -116,9 +116,7 @@ impl Crypto { protocols, tls: agent, streams: CryptoStreams::default(), - states: CryptoStates { - ..CryptoStates::default() - }, + states: CryptoStates::default(), }) } @@ -211,10 +209,10 @@ impl Crypto { Err(CryptoError::EchRetry(v)) => Err(Error::EchRetry(v)), Err(e) => { qinfo!("Handshake failed {:?}", e); - Err(match self.tls.alert() { - Some(a) => Error::CryptoAlert(*a), - _ => Error::CryptoError(e), - }) + Err(self + .tls + .alert() + .map_or(Error::CryptoError(e), |a| Error::CryptoAlert(*a))) } } } @@ -371,7 +369,7 @@ impl Crypto { rtt: u64, ) -> Option { if let Agent::Client(ref mut c) = self.tls { - if let Some(ref t) = c.resumption_token() { + c.resumption_token().as_ref().map(|t| { qtrace!("TLS token {}", hex(t.as_ref())); let mut enc = Encoder::default(); enc.encode_uint(4, version.wire_version()); @@ -382,10 +380,8 @@ impl Crypto { enc.encode_vvec(new_token.unwrap_or(&[])); enc.encode(t.as_ref()); qdebug!("resumption token {}", hex_snip_middle(enc.as_ref())); - Some(ResumptionToken::new(enc.into(), t.expiration_time())) - } else { - None - } + ResumptionToken::new(enc.into(), t.expiration_time()) + }) } else { unreachable!("It is a server."); } @@ -559,12 +555,12 @@ impl CryptoDxState { } #[must_use] - pub fn version(&self) -> Version { + pub const fn version(&self) -> Version { self.version } #[must_use] - pub fn key_phase(&self) -> bool { + pub const fn key_phase(&self) -> bool { // Epoch 3 => 0, 4 => 1, 5 => 0, 6 => 1, ... self.epoch & 1 != 1 } @@ -623,13 +619,10 @@ impl CryptoDxState { #[must_use] pub fn can_update(&self, largest_acknowledged: Option) -> bool { - if let Some(la) = largest_acknowledged { - self.used_pn.contains(&la) - } else { - // If we haven't received any acknowledgments, it's OK to update - // the first application data epoch. - self.epoch == usize::from(TLS_EPOCH_APPLICATION_DATA) - } + largest_acknowledged.map_or_else( + || self.epoch == usize::from(TLS_EPOCH_APPLICATION_DATA), + |la| self.used_pn.contains(&la), + ) } pub fn compute_mask(&self, sample: &[u8]) -> Res> { @@ -639,7 +632,7 @@ impl CryptoDxState { } #[must_use] - pub fn next_pn(&self) -> PacketNumber { + pub const fn next_pn(&self) -> PacketNumber { self.used_pn.end } @@ -670,7 +663,7 @@ impl CryptoDxState { } #[must_use] - pub fn expansion(&self) -> usize { + pub const fn expansion(&self) -> usize { self.aead.expansion() } @@ -705,7 +698,7 @@ impl CryptoDxState { /// Get the amount of extra padding packets protected with this profile need. /// This is the difference between the size of the header protection sample /// and the AEAD expansion. - pub fn extra_padding(&self) -> usize { + pub const fn extra_padding(&self) -> usize { self.hpkey .sample_size() .saturating_sub(self.aead.expansion()) @@ -747,7 +740,7 @@ impl IndexMut for CryptoState { /// `CryptoDxAppData` wraps the state necessary for one direction of application data keys. /// This includes the secret needed to generate the next set of keys. #[derive(Debug)] -pub(crate) struct CryptoDxAppData { +pub struct CryptoDxAppData { dx: CryptoDxState, cipher: Cipher, // Not the secret used to create `self.dx`, but the one needed for the next iteration. @@ -786,7 +779,7 @@ impl CryptoDxAppData { }) } - pub fn epoch(&self) -> usize { + pub const fn epoch(&self) -> usize { self.dx.epoch } } @@ -886,18 +879,15 @@ impl CryptoStates { PacketNumberSpace::Handshake => self .tx(version, CryptoSpace::Handshake) .map(|dx| (CryptoSpace::Handshake, dx)), - PacketNumberSpace::ApplicationData => { - if let Some(app) = self.app_write.as_ref() { - Some((CryptoSpace::ApplicationData, &app.dx)) - } else { - self.zero_rtt.as_ref().map(|dx| (CryptoSpace::ZeroRtt, dx)) - } - } + PacketNumberSpace::ApplicationData => self.app_write.as_ref().map_or_else( + || self.zero_rtt.as_ref().map(|dx| (CryptoSpace::ZeroRtt, dx)), + |app| Some((CryptoSpace::ApplicationData, &app.dx)), + ), } } pub fn rx_hp(&mut self, version: Version, cspace: CryptoSpace) -> Option<&mut CryptoDxState> { - if let CryptoSpace::ApplicationData = cspace { + if cspace == CryptoSpace::ApplicationData { self.app_read.as_mut().map(|ar| &mut ar.dx) } else { self.rx(version, cspace, false) @@ -1193,7 +1183,7 @@ impl CryptoStates { } #[must_use] - pub fn update_time(&self) -> Option { + pub const fn update_time(&self) -> Option { self.read_update_time } @@ -1431,7 +1421,7 @@ impl CryptoStreams { } } - fn get(&self, space: PacketNumberSpace) -> Option<&CryptoStream> { + const fn get(&self, space: PacketNumberSpace) -> Option<&CryptoStream> { let (initial, hs, app) = match self { Self::Initial { initial, diff --git a/neqo-transport/src/ecn.rs b/neqo-transport/src/ecn.rs index 10cf98163c..65b014c7cc 100644 --- a/neqo-transport/src/ecn.rs +++ b/neqo-transport/src/ecn.rs @@ -31,7 +31,7 @@ enum EcnValidationState { impl Default for EcnValidationState { fn default() -> Self { - EcnValidationState::Testing(0) + Self::Testing(0) } } @@ -54,7 +54,7 @@ impl DerefMut for EcnCount { } impl EcnCount { - pub fn new(not_ect: u64, ect0: u64, ect1: u64, ce: u64) -> Self { + pub const fn new(not_ect: u64, ect0: u64, ect1: u64, ce: u64) -> Self { // Yes, the enum array order is different from the argument order. Self(EnumMap::from_array([not_ect, ect1, ect0, ce])) } @@ -65,12 +65,12 @@ impl EcnCount { } } -impl Sub for EcnCount { - type Output = EcnCount; +impl Sub for EcnCount { + type Output = Self; /// Subtract the ECN counts in `other` from `self`. - fn sub(self, other: EcnCount) -> EcnCount { - let mut diff = EcnCount::default(); + fn sub(self, other: Self) -> Self { + let mut diff = Self::default(); for (ecn, count) in &mut *diff { *count = self[ecn].saturating_sub(other[ecn]); } @@ -103,7 +103,7 @@ impl EcnInfo { } /// Expose the current baseline. - pub fn baseline(&self) -> EcnCount { + pub const fn baseline(&self) -> EcnCount { self.baseline } @@ -216,7 +216,7 @@ impl EcnInfo { } /// The ECN mark to use for packets sent on this path. - pub fn ecn_mark(&self) -> IpTosEcn { + pub const fn ecn_mark(&self) -> IpTosEcn { match self.state { EcnValidationState::Testing { .. } | EcnValidationState::Capable => IpTosEcn::Ect0, EcnValidationState::Failed | EcnValidationState::Unknown => IpTosEcn::NotEct, diff --git a/neqo-transport/src/fc.rs b/neqo-transport/src/fc.rs index d619fd8e82..37bb3daf57 100644 --- a/neqo-transport/src/fc.rs +++ b/neqo-transport/src/fc.rs @@ -54,7 +54,7 @@ where T: Debug + Sized, { /// Make a new instance with the initial value and subject. - pub fn new(subject: T, initial: u64) -> Self { + pub const fn new(subject: T, initial: u64) -> Self { Self { subject, limit: initial, @@ -90,7 +90,7 @@ where } /// How much data has been written. - pub fn used(&self) -> u64 { + pub const fn used(&self) -> u64 { self.used } @@ -107,7 +107,7 @@ where /// This is `Some` with the active limit if `blocked` has been called, /// if a blocking frame has not been sent (or it has been lost), and /// if the blocking condition remains. - fn blocked_needed(&self) -> Option { + const fn blocked_needed(&self) -> Option { if self.blocked_frame && self.limit < self.blocked_at { Some(self.blocked_at - 1) } else { @@ -225,7 +225,7 @@ where T: Debug + Sized, { /// Make a new instance with the initial value and subject. - pub fn new(subject: T, max: u64) -> Self { + pub const fn new(subject: T, max: u64) -> Self { Self { subject, max_active: max, @@ -257,15 +257,15 @@ where } } - pub fn frame_needed(&self) -> bool { + pub const fn frame_needed(&self) -> bool { self.frame_pending } - pub fn next_limit(&self) -> u64 { + pub const fn next_limit(&self) -> u64 { self.retired + self.max_active } - pub fn max_active(&self) -> u64 { + pub const fn max_active(&self) -> u64 { self.max_active } @@ -286,11 +286,11 @@ where self.max_active = max; } - pub fn retired(&self) -> u64 { + pub const fn retired(&self) -> u64 { self.retired } - pub fn consumed(&self) -> u64 { + pub const fn consumed(&self) -> u64 { self.consumed } } @@ -424,7 +424,7 @@ impl ReceiverFlowControl { } /// Check if received item exceeds the allowed flow control limit. - pub fn check_allowed(&self, new_end: u64) -> bool { + pub const fn check_allowed(&self, new_end: u64) -> bool { new_end < self.max_allowed } @@ -444,7 +444,7 @@ pub struct RemoteStreamLimit { } impl RemoteStreamLimit { - pub fn new(stream_type: StreamType, max_streams: u64, role: Role) -> Self { + pub const fn new(stream_type: StreamType, max_streams: u64, role: Role) -> Self { Self { streams_fc: ReceiverFlowControl::new(stream_type, max_streams), // // This is for a stream created by a peer, therefore we use role.remote(). @@ -452,7 +452,7 @@ impl RemoteStreamLimit { } } - pub fn is_allowed(&self, stream_id: StreamId) -> bool { + pub const fn is_allowed(&self, stream_id: StreamId) -> bool { let stream_idx = stream_id.as_u64() >> 2; self.streams_fc.check_allowed(stream_idx) } @@ -491,7 +491,7 @@ pub struct RemoteStreamLimits { } impl RemoteStreamLimits { - pub fn new(local_max_stream_bidi: u64, local_max_stream_uni: u64, role: Role) -> Self { + pub const fn new(local_max_stream_bidi: u64, local_max_stream_uni: u64, role: Role) -> Self { Self { bidirectional: RemoteStreamLimit::new(StreamType::BiDi, local_max_stream_bidi, role), unidirectional: RemoteStreamLimit::new(StreamType::UniDi, local_max_stream_uni, role), @@ -526,7 +526,7 @@ pub struct LocalStreamLimits { } impl LocalStreamLimits { - pub fn new(role: Role) -> Self { + pub const fn new(role: Role) -> Self { Self { bidirectional: SenderFlowControl::new(StreamType::BiDi, 0), unidirectional: SenderFlowControl::new(StreamType::UniDi, 0), diff --git a/neqo-transport/src/frame.rs b/neqo-transport/src/frame.rs index 7d009f3b46..9c83868112 100644 --- a/neqo-transport/src/frame.rs +++ b/neqo-transport/src/frame.rs @@ -64,14 +64,14 @@ pub enum CloseError { } impl CloseError { - fn frame_type_bit(self) -> u64 { + const fn frame_type_bit(self) -> u64 { match self { Self::Transport(_) => 0, Self::Application(_) => 1, } } - fn from_type_bit(bit: u64, code: u64) -> Self { + const fn from_type_bit(bit: u64, code: u64) -> Self { if (bit & 0x01) == 0 { Self::Transport(code) } else { @@ -80,7 +80,7 @@ impl CloseError { } #[must_use] - pub fn code(&self) -> u64 { + pub const fn code(&self) -> u64 { match self { Self::Transport(c) | Self::Application(c) => *c, } @@ -206,14 +206,14 @@ pub enum Frame<'a> { } impl<'a> Frame<'a> { - fn get_stream_type_bit(stream_type: StreamType) -> u64 { + const fn get_stream_type_bit(stream_type: StreamType) -> u64 { match stream_type { StreamType::BiDi => 0, StreamType::UniDi => 1, } } - fn stream_type_from_bit(bit: u64) -> StreamType { + const fn stream_type_from_bit(bit: u64) -> StreamType { if (bit & 0x01) == 0 { StreamType::BiDi } else { @@ -222,7 +222,7 @@ impl<'a> Frame<'a> { } #[must_use] - pub fn get_type(&self) -> FrameType { + pub const fn get_type(&self) -> FrameType { match self { Self::Padding { .. } => FRAME_TYPE_PADDING, Self::Ping => FRAME_TYPE_PING, @@ -264,7 +264,7 @@ impl<'a> Frame<'a> { } #[must_use] - pub fn is_stream(&self) -> bool { + pub const fn is_stream(&self) -> bool { matches!( self, Self::ResetStream { .. } @@ -280,7 +280,7 @@ impl<'a> Frame<'a> { } #[must_use] - pub fn stream_type(fin: bool, nonzero_offset: bool, fill: bool) -> u64 { + pub const fn stream_type(fin: bool, nonzero_offset: bool, fill: bool) -> u64 { let mut t = FRAME_TYPE_STREAM; if fin { t |= STREAM_FRAME_BIT_FIN; @@ -297,7 +297,7 @@ impl<'a> Frame<'a> { /// If the frame causes a recipient to generate an ACK within its /// advertised maximum acknowledgement delay. #[must_use] - pub fn ack_eliciting(&self) -> bool { + pub const fn ack_eliciting(&self) -> bool { !matches!( self, Self::Ack { .. } | Self::Padding { .. } | Self::ConnectionClose { .. } @@ -307,7 +307,7 @@ impl<'a> Frame<'a> { /// If the frame can be sent in a path probe /// without initiating migration to that path. #[must_use] - pub fn path_probing(&self) -> bool { + pub const fn path_probing(&self) -> bool { matches!( self, Self::Padding { .. } diff --git a/neqo-transport/src/lib.rs b/neqo-transport/src/lib.rs index 54b08a9339..c16030d694 100644 --- a/neqo-transport/src/lib.rs +++ b/neqo-transport/src/lib.rs @@ -222,7 +222,7 @@ pub enum CloseReason { impl CloseReason { #[must_use] - pub fn app_code(&self) -> Option { + pub const fn app_code(&self) -> Option { match self { Self::Application(e) => Some(*e), Self::Transport(_) => None, @@ -232,11 +232,8 @@ impl CloseReason { /// Checks enclosed error for [`Error::NoError`] and /// [`CloseReason::Application(0)`]. #[must_use] - pub fn is_error(&self) -> bool { - !matches!( - self, - CloseReason::Transport(Error::NoError) | CloseReason::Application(0), - ) + pub const fn is_error(&self) -> bool { + !matches!(self, Self::Transport(Error::NoError) | Self::Application(0),) } } diff --git a/neqo-transport/src/packet/mod.rs b/neqo-transport/src/packet/mod.rs index 81fb53f84a..dd1bc225c5 100644 --- a/neqo-transport/src/packet/mod.rs +++ b/neqo-transport/src/packet/mod.rs @@ -82,6 +82,7 @@ impl PacketType { } } +#[allow(clippy::fallible_impl_from)] impl From for CryptoSpace { fn from(v: PacketType) -> Self { match v { @@ -230,7 +231,7 @@ impl PacketBuilder { /// Get the current limit. #[must_use] - pub fn limit(&mut self) -> usize { + pub const fn limit(&self) -> usize { self.limit } @@ -335,7 +336,7 @@ impl PacketBuilder { self.encoder.as_mut()[self.offsets.len + 1] = (len & 0xff) as u8; } - fn pad_for_crypto(&mut self, crypto: &mut CryptoDxState) { + fn pad_for_crypto(&mut self, crypto: &CryptoDxState) { // Make sure that there is enough data in the packet. // The length of the packet number plus the payload length needs to // be at least 4 (MAX_PACKET_NUMBER_LEN) plus any amount by which @@ -541,11 +542,7 @@ pub struct PublicPacket<'a> { impl<'a> PublicPacket<'a> { fn opt(v: Option) -> Res { - if let Some(v) = v { - Ok(v) - } else { - Err(Error::NoMoreData) - } + v.map_or_else(|| Err(Error::NoMoreData), |v| Ok(v)) } /// Decode the type-specific portions of a long header. @@ -709,12 +706,12 @@ impl<'a> PublicPacket<'a> { } #[must_use] - pub fn packet_type(&self) -> PacketType { + pub const fn packet_type(&self) -> PacketType { self.packet_type } #[must_use] - pub fn dcid(&self) -> ConnectionIdRef<'a> { + pub const fn dcid(&self) -> ConnectionIdRef<'a> { self.dcid } @@ -728,7 +725,7 @@ impl<'a> PublicPacket<'a> { } #[must_use] - pub fn token(&self) -> &'a [u8] { + pub const fn token(&self) -> &'a [u8] { self.token } @@ -745,11 +742,11 @@ impl<'a> PublicPacket<'a> { #[must_use] #[allow(clippy::len_without_is_empty)] // is_empty() would always return false in this case - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.data.len() } - fn decode_pn(expected: PacketNumber, pn: u64, w: usize) -> PacketNumber { + const fn decode_pn(expected: PacketNumber, pn: u64, w: usize) -> PacketNumber { let window = 1_u64 << (w * 8); let candidate = (expected & !(window - 1)) | pn; if candidate + (window / 2) <= expected { @@ -767,19 +764,19 @@ impl<'a> PublicPacket<'a> { /// Decrypt the header of the packet. fn decrypt_header( &self, - crypto: &mut CryptoDxState, + crypto: &CryptoDxState, ) -> Res<(bool, PacketNumber, Vec, &'a [u8])> { assert_ne!(self.packet_type, PacketType::Retry); assert_ne!(self.packet_type, PacketType::VersionNegotiation); let sample_offset = self.header_len + SAMPLE_OFFSET; - let mask = if let Some(sample) = self.data.get(sample_offset..(sample_offset + SAMPLE_SIZE)) - { - qtrace!("unmask hdr={}", hex(&self.data[..sample_offset])); - crypto.compute_mask(sample) - } else { - Err(Error::NoMoreData) - }?; + let mask = self + .data + .get(sample_offset..(sample_offset + SAMPLE_SIZE)) + .map_or(Err(Error::NoMoreData), |sample| { + qtrace!("unmask hdr={}", hex(&self.data[..sample_offset])); + crypto.compute_mask(sample) + })?; // Un-mask the leading byte. let bits = if self.packet_type == PacketType::Short { @@ -900,17 +897,17 @@ pub struct DecryptedPacket { impl DecryptedPacket { #[must_use] - pub fn version(&self) -> Version { + pub const fn version(&self) -> Version { self.version } #[must_use] - pub fn packet_type(&self) -> PacketType { + pub const fn packet_type(&self) -> PacketType { self.pt } #[must_use] - pub fn pn(&self) -> PacketNumber { + pub const fn pn(&self) -> PacketNumber { self.pn } } @@ -942,7 +939,7 @@ mod tests { const SERVER_CID: &[u8] = &[0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5]; /// This is a connection ID manager, which is only used for decoding short header packets. - fn cid_mgr() -> RandomConnectionIdGenerator { + const fn cid_mgr() -> RandomConnectionIdGenerator { RandomConnectionIdGenerator::new(SERVER_CID.len()) } diff --git a/neqo-transport/src/packet/retry.rs b/neqo-transport/src/packet/retry.rs index 71193b9100..20381765be 100644 --- a/neqo-transport/src/packet/retry.rs +++ b/neqo-transport/src/packet/retry.rs @@ -48,9 +48,6 @@ where /// Determine how large the expansion is for a given key. pub fn expansion(version: Version) -> usize { - if let Ok(ex) = use_aead(version, |aead| Ok(aead.expansion())) { - ex - } else { - panic!("Unable to access Retry AEAD") - } + use_aead(version, |aead| Ok(aead.expansion())) + .unwrap_or_else(|_| panic!("Unable to access Retry AEAD")) } diff --git a/neqo-transport/src/path.rs b/neqo-transport/src/path.rs index ef222fd8d7..cee105a5ed 100644 --- a/neqo-transport/src/path.rs +++ b/neqo-transport/src/path.rs @@ -211,10 +211,9 @@ impl Paths { #[must_use] fn select_primary(&mut self, path: &PathRef) -> Option { qdebug!([path.borrow()], "set as primary path"); - let old_path = self - .primary - .replace(Rc::clone(path)) - .inspect(|old| old.borrow_mut().set_primary(false)); + let old_path = self.primary.replace(Rc::clone(path)).inspect(|old| { + old.borrow_mut().set_primary(false); + }); // Swap the primary path into slot 0, so that it is protected from eviction. let idx = self @@ -276,6 +275,7 @@ impl Paths { if primary_failed { self.primary = None; // Find a valid path to fall back to. + #[allow(clippy::option_if_let_else)] if let Some(fallback) = self .paths .iter() @@ -437,13 +437,13 @@ impl Paths { self.to_retire.retain(|&seqno| seqno != acked); } - pub fn lost_ack_frequency(&mut self, lost: &AckRate) { + pub fn lost_ack_frequency(&self, lost: &AckRate) { if let Some(path) = self.primary() { path.borrow_mut().lost_ack_frequency(lost); } } - pub fn acked_ack_frequency(&mut self, acked: &AckRate) { + pub fn acked_ack_frequency(&self, acked: &AckRate) { if let Some(path) = self.primary() { path.borrow_mut().acked_ack_frequency(acked); } @@ -494,7 +494,7 @@ enum ProbeState { impl ProbeState { /// Determine whether the current state requires probing. - fn probe_needed(&self) -> bool { + const fn probe_needed(&self) -> bool { matches!(self, Self::ProbeNeeded { .. }) } } @@ -588,12 +588,12 @@ impl Path { } /// Whether this path is the primary or current path for the connection. - pub fn is_primary(&self) -> bool { + pub const fn is_primary(&self) -> bool { self.primary } /// Whether this path is a temporary one. - pub fn is_temporary(&self) -> bool { + pub const fn is_temporary(&self) -> bool { self.remote_cid.is_none() } @@ -652,7 +652,7 @@ impl Path { } } - fn mtu_by_addr(addr: IpAddr) -> usize { + const fn mtu_by_addr(addr: IpAddr) -> usize { match addr { IpAddr::V4(_) => PATH_MTU_V4, IpAddr::V6(_) => PATH_MTU_V6, @@ -660,7 +660,7 @@ impl Path { } /// Get the path MTU. This is currently fixed based on IP version. - pub fn mtu(&self) -> usize { + pub const fn mtu(&self) -> usize { Self::mtu_by_addr(self.remote.ip()) } @@ -712,17 +712,17 @@ impl Path { } /// Get local address as `SocketAddr` - pub fn local_address(&self) -> SocketAddr { + pub const fn local_address(&self) -> SocketAddr { self.local } /// Get remote address as `SocketAddr` - pub fn remote_address(&self) -> SocketAddr { + pub const fn remote_address(&self) -> SocketAddr { self.remote } /// Whether the path has been validated. - pub fn is_valid(&self) -> bool { + pub const fn is_valid(&self) -> bool { self.validated.is_some() } @@ -769,7 +769,7 @@ impl Path { } /// Returns true if this path have any probing frames to send. - pub fn has_probe(&self) -> bool { + pub const fn has_probe(&self) -> bool { self.challenge.is_some() || self.state.probe_needed() } @@ -852,13 +852,13 @@ impl Path { self.probe(); } } - if let ProbeState::Failed = self.state { + if matches!(self.state, ProbeState::Failed) { // Retire failed paths immediately. false } else if self.primary { // Keep valid primary paths otherwise. true - } else if let ProbeState::Valid = self.state { + } else if matches!(self.state, ProbeState::Valid) { // Retire validated, non-primary paths. // Allow more than `MAX_PATH_PROBES` times the PTO so that an old // path remains around until after a previous path fails. @@ -883,7 +883,7 @@ impl Path { } /// Get the RTT estimator for this path. - pub fn rtt(&self) -> &RttEstimate { + pub const fn rtt(&self) -> &RttEstimate { &self.rtt } @@ -893,7 +893,7 @@ impl Path { } /// Read-only access to the owned sender. - pub fn sender(&self) -> &PacketSender { + pub const fn sender(&self) -> &PacketSender { &self.sender } @@ -959,7 +959,7 @@ impl Path { ); stats.rtt_init_guess = true; self.rtt.update( - &mut self.qlog, + &self.qlog, now - sent.time_sent(), Duration::new(0, 0), false, diff --git a/neqo-transport/src/qlog.rs b/neqo-transport/src/qlog.rs index 7d28d94d96..09a423965a 100644 --- a/neqo-transport/src/qlog.rs +++ b/neqo-transport/src/qlog.rs @@ -33,7 +33,7 @@ use crate::{ version::{Version, VersionConfig, WireVersion}, }; -pub fn connection_tparams_set(qlog: &mut NeqoQlog, tph: &TransportParametersHandler) { +pub fn connection_tparams_set(qlog: &NeqoQlog, tph: &TransportParametersHandler) { qlog.add_event_data(|| { let remote = tph.remote(); #[allow(clippy::cast_possible_truncation)] // Nope. @@ -82,15 +82,15 @@ pub fn connection_tparams_set(qlog: &mut NeqoQlog, tph: &TransportParametersHand }); } -pub fn server_connection_started(qlog: &mut NeqoQlog, path: &PathRef) { +pub fn server_connection_started(qlog: &NeqoQlog, path: &PathRef) { connection_started(qlog, path); } -pub fn client_connection_started(qlog: &mut NeqoQlog, path: &PathRef) { +pub fn client_connection_started(qlog: &NeqoQlog, path: &PathRef) { connection_started(qlog, path); } -fn connection_started(qlog: &mut NeqoQlog, path: &PathRef) { +fn connection_started(qlog: &NeqoQlog, path: &PathRef) { qlog.add_event_data(|| { let p = path.deref().borrow(); let ev_data = EventData::ConnectionStarted(ConnectionStarted { @@ -112,7 +112,7 @@ fn connection_started(qlog: &mut NeqoQlog, path: &PathRef) { }); } -pub fn connection_state_updated(qlog: &mut NeqoQlog, new: &State) { +pub fn connection_state_updated(qlog: &NeqoQlog, new: &State) { qlog.add_event_data(|| { let ev_data = EventData::ConnectionStateUpdated(ConnectionStateUpdated { old: None, @@ -131,7 +131,7 @@ pub fn connection_state_updated(qlog: &mut NeqoQlog, new: &State) { }); } -pub fn client_version_information_initiated(qlog: &mut NeqoQlog, version_config: &VersionConfig) { +pub fn client_version_information_initiated(qlog: &NeqoQlog, version_config: &VersionConfig) { qlog.add_event_data(|| { Some(EventData::VersionInformation(VersionInformation { client_versions: Some( @@ -148,7 +148,7 @@ pub fn client_version_information_initiated(qlog: &mut NeqoQlog, version_config: } pub fn client_version_information_negotiated( - qlog: &mut NeqoQlog, + qlog: &NeqoQlog, client: &[Version], server: &[WireVersion], chosen: Version, @@ -167,11 +167,7 @@ pub fn client_version_information_negotiated( }); } -pub fn server_version_information_failed( - qlog: &mut NeqoQlog, - server: &[Version], - client: WireVersion, -) { +pub fn server_version_information_failed(qlog: &NeqoQlog, server: &[Version], client: WireVersion) { qlog.add_event_data(|| { Some(EventData::VersionInformation(VersionInformation { client_versions: Some(vec![format!("{client:02x}")]), @@ -186,13 +182,7 @@ pub fn server_version_information_failed( }); } -pub fn packet_sent( - qlog: &mut NeqoQlog, - pt: PacketType, - pn: PacketNumber, - plen: usize, - body: &[u8], -) { +pub fn packet_sent(qlog: &NeqoQlog, pt: PacketType, pn: PacketNumber, plen: usize, body: &[u8]) { qlog.add_event_with_stream(|stream| { let mut d = Decoder::from(body); let header = PacketHeader::with_type(pt.into(), Some(pn), None, None, None); @@ -229,7 +219,7 @@ pub fn packet_sent( }); } -pub fn packet_dropped(qlog: &mut NeqoQlog, public_packet: &PublicPacket) { +pub fn packet_dropped(qlog: &NeqoQlog, public_packet: &PublicPacket) { qlog.add_event_data(|| { let header = PacketHeader::with_type(public_packet.packet_type().into(), None, None, None, None); @@ -251,7 +241,7 @@ pub fn packet_dropped(qlog: &mut NeqoQlog, public_packet: &PublicPacket) { }); } -pub fn packets_lost(qlog: &mut NeqoQlog, pkts: &[SentPacket]) { +pub fn packets_lost(qlog: &NeqoQlog, pkts: &[SentPacket]) { qlog.add_event_with_stream(|stream| { for pkt in pkts { let header = @@ -269,11 +259,7 @@ pub fn packets_lost(qlog: &mut NeqoQlog, pkts: &[SentPacket]) { }); } -pub fn packet_received( - qlog: &mut NeqoQlog, - public_packet: &PublicPacket, - payload: &DecryptedPacket, -) { +pub fn packet_received(qlog: &NeqoQlog, public_packet: &PublicPacket, payload: &DecryptedPacket) { qlog.add_event_with_stream(|stream| { let mut d = Decoder::from(&payload[..]); @@ -333,7 +319,7 @@ pub enum QlogMetric { PacingRate(u64), } -pub fn metrics_updated(qlog: &mut NeqoQlog, updated_metrics: &[QlogMetric]) { +pub fn metrics_updated(qlog: &NeqoQlog, updated_metrics: &[QlogMetric]) { debug_assert!(!updated_metrics.is_empty()); qlog.add_event_data(|| { @@ -391,11 +377,11 @@ pub fn metrics_updated(qlog: &mut NeqoQlog, updated_metrics: &[QlogMetric]) { impl From> for QuicFrame { fn from(frame: Frame) -> Self { match frame { - Frame::Padding(len) => QuicFrame::Padding { + Frame::Padding(len) => Self::Padding { length: None, payload_length: u32::from(len), }, - Frame::Ping => QuicFrame::Ping { + Frame::Ping => Self::Ping { length: None, payload_length: None, }, @@ -418,7 +404,7 @@ impl From> for QuicFrame { ) }); - QuicFrame::Ack { + Self::Ack { ack_delay: Some(ack_delay as f32 / 1000.0), acked_ranges, ect1: ecn_count.map(|c| c[IpTosEcn::Ect1]), @@ -432,7 +418,7 @@ impl From> for QuicFrame { stream_id, application_error_code, final_size, - } => QuicFrame::ResetStream { + } => Self::ResetStream { stream_id: stream_id.as_u64(), error_code: application_error_code, final_size, @@ -442,17 +428,17 @@ impl From> for QuicFrame { Frame::StopSending { stream_id, application_error_code, - } => QuicFrame::StopSending { + } => Self::StopSending { stream_id: stream_id.as_u64(), error_code: application_error_code, length: None, payload_length: None, }, - Frame::Crypto { offset, data } => QuicFrame::Crypto { + Frame::Crypto { offset, data } => Self::Crypto { offset, length: data.len() as u64, }, - Frame::NewToken { token } => QuicFrame::NewToken { + Frame::NewToken { token } => Self::NewToken { token: qlog::Token { ty: Some(qlog::TokenType::Retry), details: None, @@ -469,45 +455,45 @@ impl From> for QuicFrame { offset, data, .. - } => QuicFrame::Stream { + } => Self::Stream { stream_id: stream_id.as_u64(), offset, length: data.len() as u64, fin: Some(fin), raw: None, }, - Frame::MaxData { maximum_data } => QuicFrame::MaxData { + Frame::MaxData { maximum_data } => Self::MaxData { maximum: maximum_data, }, Frame::MaxStreamData { stream_id, maximum_stream_data, - } => QuicFrame::MaxStreamData { + } => Self::MaxStreamData { stream_id: stream_id.as_u64(), maximum: maximum_stream_data, }, Frame::MaxStreams { stream_type, maximum_streams, - } => QuicFrame::MaxStreams { + } => Self::MaxStreams { stream_type: match stream_type { NeqoStreamType::BiDi => StreamType::Bidirectional, NeqoStreamType::UniDi => StreamType::Unidirectional, }, maximum: maximum_streams, }, - Frame::DataBlocked { data_limit } => QuicFrame::DataBlocked { limit: data_limit }, + Frame::DataBlocked { data_limit } => Self::DataBlocked { limit: data_limit }, Frame::StreamDataBlocked { stream_id, stream_data_limit, - } => QuicFrame::StreamDataBlocked { + } => Self::StreamDataBlocked { stream_id: stream_id.as_u64(), limit: stream_data_limit, }, Frame::StreamsBlocked { stream_type, stream_limit, - } => QuicFrame::StreamsBlocked { + } => Self::StreamsBlocked { stream_type: match stream_type { NeqoStreamType::BiDi => StreamType::Bidirectional, NeqoStreamType::UniDi => StreamType::Unidirectional, @@ -519,27 +505,27 @@ impl From> for QuicFrame { retire_prior, connection_id, stateless_reset_token, - } => QuicFrame::NewConnectionId { + } => Self::NewConnectionId { sequence_number: sequence_number as u32, retire_prior_to: retire_prior as u32, connection_id_length: Some(connection_id.len() as u8), connection_id: hex(connection_id), stateless_reset_token: Some(hex(stateless_reset_token)), }, - Frame::RetireConnectionId { sequence_number } => QuicFrame::RetireConnectionId { + Frame::RetireConnectionId { sequence_number } => Self::RetireConnectionId { sequence_number: sequence_number as u32, }, - Frame::PathChallenge { data } => QuicFrame::PathChallenge { + Frame::PathChallenge { data } => Self::PathChallenge { data: Some(hex(data)), }, - Frame::PathResponse { data } => QuicFrame::PathResponse { + Frame::PathResponse { data } => Self::PathResponse { data: Some(hex(data)), }, Frame::ConnectionClose { error_code, frame_type, reason_phrase, - } => QuicFrame::ConnectionClose { + } => Self::ConnectionClose { error_space: match error_code { CloseError::Transport(_) => Some(ErrorSpace::TransportError), CloseError::Application(_) => Some(ErrorSpace::ApplicationError), @@ -549,13 +535,13 @@ impl From> for QuicFrame { reason: Some(reason_phrase), trigger_frame_type: Some(frame_type), }, - Frame::HandshakeDone => QuicFrame::HandshakeDone, - Frame::AckFrequency { .. } => QuicFrame::Unknown { + Frame::HandshakeDone => Self::HandshakeDone, + Frame::AckFrequency { .. } => Self::Unknown { frame_type_value: None, raw_frame_type: frame.get_type(), raw: None, }, - Frame::Datagram { data, .. } => QuicFrame::Datagram { + Frame::Datagram { data, .. } => Self::Datagram { length: data.len() as u64, raw: None, }, @@ -566,13 +552,13 @@ impl From> for QuicFrame { impl From for qlog::events::quic::PacketType { fn from(value: PacketType) -> Self { match value { - PacketType::Initial => qlog::events::quic::PacketType::Initial, - PacketType::Handshake => qlog::events::quic::PacketType::Handshake, - PacketType::ZeroRtt => qlog::events::quic::PacketType::ZeroRtt, - PacketType::Short => qlog::events::quic::PacketType::OneRtt, - PacketType::Retry => qlog::events::quic::PacketType::Retry, - PacketType::VersionNegotiation => qlog::events::quic::PacketType::VersionNegotiation, - PacketType::OtherVersion => qlog::events::quic::PacketType::Unknown, + PacketType::Initial => Self::Initial, + PacketType::Handshake => Self::Handshake, + PacketType::ZeroRtt => Self::ZeroRtt, + PacketType::Short => Self::OneRtt, + PacketType::Retry => Self::Retry, + PacketType::VersionNegotiation => Self::VersionNegotiation, + PacketType::OtherVersion => Self::Unknown, } } } diff --git a/neqo-transport/src/quic_datagrams.rs b/neqo-transport/src/quic_datagrams.rs index d7c4769e31..af82d8124e 100644 --- a/neqo-transport/src/quic_datagrams.rs +++ b/neqo-transport/src/quic_datagrams.rs @@ -28,10 +28,7 @@ pub enum DatagramTracking { impl From> for DatagramTracking { fn from(v: Option) -> Self { - match v { - Some(id) => Self::Id(id), - None => Self::None, - } + v.map_or(Self::None, Self::Id) } } @@ -50,7 +47,7 @@ struct QuicDatagram { } impl QuicDatagram { - fn tracking(&self) -> &DatagramTracking { + const fn tracking(&self) -> &DatagramTracking { &self.tracking } } @@ -93,7 +90,7 @@ impl QuicDatagrams { } } - pub fn remote_datagram_size(&self) -> u64 { + pub const fn remote_datagram_size(&self) -> u64 { self.remote_datagram_size } diff --git a/neqo-transport/src/recovery/mod.rs b/neqo-transport/src/recovery/mod.rs index 5768fccab4..bec3664118 100644 --- a/neqo-transport/src/recovery/mod.rs +++ b/neqo-transport/src/recovery/mod.rs @@ -32,19 +32,19 @@ use crate::{ tracking::{PacketNumberSpace, PacketNumberSpaceSet}, }; -pub(crate) const PACKET_THRESHOLD: u64 = 3; +pub const PACKET_THRESHOLD: u64 = 3; /// `ACK_ONLY_SIZE_LIMIT` is the minimum size of the congestion window. /// If the congestion window is this small, we will only send ACK frames. -pub(crate) const ACK_ONLY_SIZE_LIMIT: usize = 256; +pub const ACK_ONLY_SIZE_LIMIT: usize = 256; /// The maximum number of packets we send on a PTO. /// And the maximum number to declare lost when the PTO timer is hit. pub const MAX_PTO_PACKET_COUNT: usize = 2; /// The preferred limit on the number of packets that are tracked. /// If we exceed this number, we start sending `PING` frames sooner to /// force the peer to acknowledge some of them. -pub(crate) const MAX_OUTSTANDING_UNACK: usize = 200; +pub const MAX_OUTSTANDING_UNACK: usize = 200; /// Disable PING until this many packets are outstanding. -pub(crate) const MIN_OUTSTANDING_UNACK: usize = 16; +pub const MIN_OUTSTANDING_UNACK: usize = 16; /// The scale we use for the fast PTO feature. pub const FAST_PTO_SCALE: u8 = 100; @@ -110,17 +110,17 @@ impl SendProfile { self.limit < ACK_ONLY_SIZE_LIMIT || self.pto.map_or(false, |sp| space < sp) } - pub fn paced(&self) -> bool { + pub const fn paced(&self) -> bool { self.paced } - pub fn limit(&self) -> usize { + pub const fn limit(&self) -> usize { self.limit } } #[derive(Debug)] -pub(crate) struct LossRecoverySpace { +pub struct LossRecoverySpace { space: PacketNumberSpace, largest_acked: Option, largest_acked_sent_time: Option, @@ -154,7 +154,7 @@ impl LossRecoverySpace { } #[must_use] - pub fn space(&self) -> PacketNumberSpace { + pub const fn space(&self) -> PacketNumberSpace { self.space } @@ -162,11 +162,11 @@ impl LossRecoverySpace { /// largest acknowledged and that isn't yet declared lost. /// Use the value we prepared earlier in `detect_lost_packets`. #[must_use] - pub fn loss_recovery_timer_start(&self) -> Option { + pub const fn loss_recovery_timer_start(&self) -> Option { self.first_ooo_time } - pub fn in_flight_outstanding(&self) -> bool { + pub const fn in_flight_outstanding(&self) -> bool { self.in_flight_outstanding > 0 } @@ -360,14 +360,14 @@ impl LossRecoverySpace { } #[derive(Debug)] -pub(crate) struct LossRecoverySpaces { +pub struct LossRecoverySpaces { /// When we have all of the loss recovery spaces, this will use a separate /// allocation, but this is reduced once the handshake is done. spaces: SmallVec<[LossRecoverySpace; 1]>, } impl LossRecoverySpaces { - fn idx(space: PacketNumberSpace) -> usize { + const fn idx(space: PacketNumberSpace) -> usize { match space { PacketNumberSpace::ApplicationData => 0, PacketNumberSpace::Handshake => 1, @@ -468,7 +468,7 @@ impl PtoState { self.probe = probe; } - pub fn count(&self) -> usize { + pub const fn count(&self) -> usize { self.count } @@ -490,7 +490,7 @@ impl PtoState { } #[derive(Debug)] -pub(crate) struct LossRecovery { +pub struct LossRecovery { /// When the handshake was confirmed, if it has been. confirmed_time: Option, pto_state: Option, @@ -569,7 +569,7 @@ impl LossRecovery { /// Record an RTT sample. fn rtt_sample( - &mut self, + &self, rtt: &mut RttEstimate, send_time: Instant, now: Instant, @@ -577,7 +577,7 @@ impl LossRecovery { ) { let confirmed = self.confirmed_time.map_or(false, |t| t < send_time); if let Some(sample) = now.checked_duration_since(send_time) { - rtt.update(&mut self.qlog, sample, ack_delay, confirmed, now); + rtt.update(&self.qlog, sample, ack_delay, confirmed, now); } } @@ -817,7 +817,7 @@ impl LossRecovery { .count_pto(&mut self.stats.borrow_mut()); qlog::metrics_updated( - &mut self.qlog, + &self.qlog, &[QlogMetric::PtoCount( self.pto_state.as_ref().unwrap().count(), )], @@ -1003,7 +1003,7 @@ mod tests { self.lr.timeout(&self.path, now) } - pub fn next_timeout(&mut self) -> Option { + pub fn next_timeout(&self) -> Option { self.lr.next_timeout(self.path.borrow().rtt()) } diff --git a/neqo-transport/src/recovery/sent.rs b/neqo-transport/src/recovery/sent.rs index 1a7be9dd4a..999ab14d2d 100644 --- a/neqo-transport/src/recovery/sent.rs +++ b/neqo-transport/src/recovery/sent.rs @@ -37,7 +37,7 @@ pub struct SentPacket { } impl SentPacket { - pub fn new( + pub const fn new( pt: PacketType, pn: PacketNumber, ecn_mark: IpTosEcn, @@ -61,37 +61,37 @@ impl SentPacket { } /// The type of this packet. - pub fn packet_type(&self) -> PacketType { + pub const fn packet_type(&self) -> PacketType { self.pt } /// The number of the packet. - pub fn pn(&self) -> PacketNumber { + pub const fn pn(&self) -> PacketNumber { self.pn } /// The ECN mark of the packet. - pub fn ecn_mark(&self) -> IpTosEcn { + pub const fn ecn_mark(&self) -> IpTosEcn { self.ecn_mark } /// The time that this packet was sent. - pub fn time_sent(&self) -> Instant { + pub const fn time_sent(&self) -> Instant { self.time_sent } /// Returns `true` if the packet will elicit an ACK. - pub fn ack_eliciting(&self) -> bool { + pub const fn ack_eliciting(&self) -> bool { self.ack_eliciting } /// Returns `true` if the packet was sent on the primary path. - pub fn on_primary_path(&self) -> bool { + pub const fn on_primary_path(&self) -> bool { self.primary_path } /// The length of the packet that was sent. - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.len } @@ -113,7 +113,7 @@ impl SentPacket { } /// Whether the packet has been declared lost. - pub fn lost(&self) -> bool { + pub const fn lost(&self) -> bool { self.time_declared_lost.is_some() } @@ -123,12 +123,12 @@ impl SentPacket { /// and has not previously been declared lost. /// Note that this should count packets that contain only ACK and PADDING, /// but we don't send PADDING, so we don't track that. - pub fn cc_outstanding(&self) -> bool { + pub const fn cc_outstanding(&self) -> bool { self.ack_eliciting() && self.on_primary_path() && !self.lost() } /// Whether the packet should be tracked as in-flight. - pub fn cc_in_flight(&self) -> bool { + pub const fn cc_in_flight(&self) -> bool { self.ack_eliciting() && self.on_primary_path() } @@ -150,7 +150,7 @@ impl SentPacket { } /// Whether the packet contents were cleared out after a PTO. - pub fn pto_fired(&self) -> bool { + pub const fn pto_fired(&self) -> bool { self.pto } diff --git a/neqo-transport/src/recv_stream.rs b/neqo-transport/src/recv_stream.rs index 5da80d6004..d0d9c9192d 100644 --- a/neqo-transport/src/recv_stream.rs +++ b/neqo-transport/src/recv_stream.rs @@ -37,7 +37,7 @@ const RX_STREAM_DATA_WINDOW: u64 = 0x10_0000; // 1MiB pub const RECV_BUFFER_SIZE: usize = RX_STREAM_DATA_WINDOW as usize; #[derive(Debug, Default)] -pub(crate) struct RecvStreams { +pub struct RecvStreams { streams: BTreeMap, keep_alive: Weak<()>, } @@ -61,10 +61,11 @@ impl RecvStreams { self.streams.insert(id, stream); } + #[allow(clippy::missing_errors_doc)] pub fn get_mut(&mut self, id: StreamId) -> Res<&mut RecvStream> { self.streams.get_mut(&id).ok_or(Error::InvalidStreamId) } - + #[allow(clippy::missing_errors_doc)] pub fn keep_alive(&mut self, id: StreamId, k: bool) -> Res<()> { let self_ka = &mut self.keep_alive; let s = self.streams.get_mut(&id).ok_or(Error::InvalidStreamId)?; @@ -80,7 +81,8 @@ impl RecvStreams { Ok(()) } - pub fn need_keep_alive(&mut self) -> bool { + #[must_use] + pub fn need_keep_alive(&self) -> bool { self.keep_alive.strong_count() > 0 } @@ -314,12 +316,12 @@ impl RxStreamOrderer { /// Bytes read by the application. #[must_use] - pub fn retired(&self) -> u64 { + pub const fn retired(&self) -> u64 { self.retired } #[must_use] - pub fn received(&self) -> u64 { + pub const fn received(&self) -> u64 { self.received } @@ -441,7 +443,7 @@ impl RecvStreamState { } } - fn name(&self) -> &str { + const fn name(&self) -> &str { match self { Self::Recv { .. } => "Recv", Self::SizeKnown { .. } => "SizeKnown", @@ -453,7 +455,7 @@ impl RecvStreamState { } } - fn recv_buf(&self) -> Option<&RxStreamOrderer> { + const fn recv_buf(&self) -> Option<&RxStreamOrderer> { match self { Self::Recv { recv_buf, .. } | Self::SizeKnown { recv_buf, .. } @@ -525,7 +527,7 @@ pub struct RecvStreamStats { impl RecvStreamStats { #[must_use] - pub fn new(bytes_received: u64, bytes_read: u64) -> Self { + pub const fn new(bytes_received: u64, bytes_read: u64) -> Self { Self { bytes_received, bytes_read, @@ -533,12 +535,12 @@ impl RecvStreamStats { } #[must_use] - pub fn bytes_received(&self) -> u64 { + pub const fn bytes_received(&self) -> u64 { self.bytes_received } #[must_use] - pub fn bytes_read(&self) -> u64 { + pub const fn bytes_read(&self) -> u64 { self.bytes_read } } @@ -598,7 +600,7 @@ impl RecvStream { } #[must_use] - pub fn stats(&self) -> RecvStreamStats { + pub const fn stats(&self) -> RecvStreamStats { match &self.state { RecvStreamState::Recv { recv_buf, .. } | RecvStreamState::SizeKnown { recv_buf, .. } @@ -767,7 +769,7 @@ impl RecvStream { fn flow_control_retire_data( new_read: u64, fc: &mut ReceiverFlowControl, - session_fc: &mut Rc>>, + session_fc: &Rc>>, ) { if new_read > 0 { fc.add_retired(new_read); @@ -791,7 +793,7 @@ impl RecvStream { } #[must_use] - pub fn is_terminal(&self) -> bool { + pub const fn is_terminal(&self) -> bool { matches!( self.state, RecvStreamState::ResetRecvd { .. } | RecvStreamState::DataRead { .. } @@ -799,7 +801,7 @@ impl RecvStream { } // App got all data but did not get the fin signal. - fn needs_to_inform_app_about_fin(&self) -> bool { + const fn needs_to_inform_app_about_fin(&self) -> bool { matches!(self.state, RecvStreamState::DataRecvd { .. }) } @@ -986,7 +988,7 @@ impl RecvStream { #[cfg(test)] #[must_use] - pub fn has_frames_to_write(&self) -> bool { + pub const fn has_frames_to_write(&self) -> bool { if let RecvStreamState::Recv { fc, .. } = &self.state { fc.frame_needed() } else { @@ -996,7 +998,7 @@ impl RecvStream { #[cfg(test)] #[must_use] - pub fn fc(&self) -> Option<&ReceiverFlowControl> { + pub const fn fc(&self) -> Option<&ReceiverFlowControl> { match &self.state { RecvStreamState::Recv { fc, .. } | RecvStreamState::SizeKnown { fc, .. } @@ -1339,7 +1341,7 @@ mod tests { s.read(&mut buf).unwrap_err(); } - fn check_chunks(s: &mut RxStreamOrderer, expected: &[(u64, usize)]) { + fn check_chunks(s: &RxStreamOrderer, expected: &[(u64, usize)]) { assert_eq!(s.data_ranges.len(), expected.len()); for ((start, buf), (expected_start, expected_len)) in s.data_ranges.iter().zip(expected) { assert_eq!((*start, buf.len()), (*expected_start, *expected_len)); @@ -1352,27 +1354,27 @@ mod tests { let mut s = RxStreamOrderer::new(); s.inbound_frame(0, &[1; 6]); - check_chunks(&mut s, &[(0, 6)]); + check_chunks(&s, &[(0, 6)]); // New data that overlaps entirely (starting from the head), is ignored. s.inbound_frame(0, &[2; 3]); - check_chunks(&mut s, &[(0, 6)]); + check_chunks(&s, &[(0, 6)]); // New data that overlaps at the tail has any new data appended. s.inbound_frame(2, &[3; 6]); - check_chunks(&mut s, &[(0, 8)]); + check_chunks(&s, &[(0, 8)]); // New data that overlaps entirely (up to the tail), is ignored. s.inbound_frame(4, &[4; 4]); - check_chunks(&mut s, &[(0, 8)]); + check_chunks(&s, &[(0, 8)]); // New data that overlaps, starting from the beginning is appended too. s.inbound_frame(0, &[5; 10]); - check_chunks(&mut s, &[(0, 10)]); + check_chunks(&s, &[(0, 10)]); // New data that is entirely subsumed is ignored. s.inbound_frame(2, &[6; 2]); - check_chunks(&mut s, &[(0, 10)]); + check_chunks(&s, &[(0, 10)]); let mut buf = [0; 16]; assert_eq!(s.read(&mut buf[..]), 10); @@ -1385,15 +1387,15 @@ mod tests { let mut s = RxStreamOrderer::new(); s.inbound_frame(1, &[6; 6]); - check_chunks(&mut s, &[(1, 6)]); + check_chunks(&s, &[(1, 6)]); // Insertion before an existing chunk causes truncation of the new chunk. s.inbound_frame(0, &[7; 6]); - check_chunks(&mut s, &[(0, 1), (1, 6)]); + check_chunks(&s, &[(0, 1), (1, 6)]); // Perfect overlap with existing slices has no effect. s.inbound_frame(0, &[8; 7]); - check_chunks(&mut s, &[(0, 1), (1, 6)]); + check_chunks(&s, &[(0, 1), (1, 6)]); let mut buf = [0; 16]; assert_eq!(s.read(&mut buf[..]), 7); @@ -1405,16 +1407,16 @@ mod tests { let mut s = RxStreamOrderer::new(); s.inbound_frame(1, &[6; 6]); - check_chunks(&mut s, &[(1, 6)]); + check_chunks(&s, &[(1, 6)]); // Insertion before an existing chunk causes truncation of the new chunk. s.inbound_frame(0, &[7; 6]); - check_chunks(&mut s, &[(0, 1), (1, 6)]); + check_chunks(&s, &[(0, 1), (1, 6)]); // New data at the end causes the tail to be added to the first chunk, // replacing later chunks entirely. s.inbound_frame(0, &[9; 8]); - check_chunks(&mut s, &[(0, 8)]); + check_chunks(&s, &[(0, 8)]); let mut buf = [0; 16]; assert_eq!(s.read(&mut buf[..]), 8); @@ -1426,15 +1428,15 @@ mod tests { let mut s = RxStreamOrderer::new(); s.inbound_frame(2, &[6; 6]); - check_chunks(&mut s, &[(2, 6)]); + check_chunks(&s, &[(2, 6)]); // Insertion before an existing chunk causes truncation of the new chunk. s.inbound_frame(1, &[7; 6]); - check_chunks(&mut s, &[(1, 1), (2, 6)]); + check_chunks(&s, &[(1, 1), (2, 6)]); // New data at the start and end replaces all the slices. s.inbound_frame(0, &[9; 10]); - check_chunks(&mut s, &[(0, 10)]); + check_chunks(&s, &[(0, 10)]); let mut buf = [0; 16]; assert_eq!(s.read(&mut buf[..]), 10); @@ -1450,11 +1452,11 @@ mod tests { // Partially read slices are retained. assert_eq!(s.read(&mut buf[..6]), 6); - check_chunks(&mut s, &[(0, 10)]); + check_chunks(&s, &[(0, 10)]); // Partially read slices are kept and so are added to. s.inbound_frame(3, &buf[..10]); - check_chunks(&mut s, &[(0, 13)]); + check_chunks(&s, &[(0, 13)]); // Wholly read pieces are dropped. assert_eq!(s.read(&mut buf[..]), 7); @@ -1462,7 +1464,7 @@ mod tests { // New data that overlaps with retired data is trimmed. s.inbound_frame(0, &buf[..]); - check_chunks(&mut s, &[(13, 5)]); + check_chunks(&s, &[(13, 5)]); } #[test] diff --git a/neqo-transport/src/rtt.rs b/neqo-transport/src/rtt.rs index 3b2969f689..736a229bb4 100644 --- a/neqo-transport/src/rtt.rs +++ b/neqo-transport/src/rtt.rs @@ -26,7 +26,7 @@ use crate::{ /// `select()`, or similar) can reliably deliver; see `neqo_common::hrtime`. pub const GRANULARITY: Duration = Duration::from_millis(1); // Defined in -recovery 6.2 as 333ms but using lower value. -pub(crate) const INITIAL_RTT: Duration = Duration::from_millis(100); +pub const INITIAL_RTT: Duration = Duration::from_millis(100); #[derive(Debug)] #[allow(clippy::module_name_repetitions)] @@ -85,7 +85,7 @@ impl RttEstimate { pub fn update( &mut self, - qlog: &mut NeqoQlog, + qlog: &NeqoQlog, mut rtt_sample: Duration, ack_delay: Duration, confirmed: bool, @@ -138,7 +138,7 @@ impl RttEstimate { } /// Get the estimated value. - pub fn estimate(&self) -> Duration { + pub const fn estimate(&self) -> Duration { self.smoothed_rtt } @@ -160,20 +160,20 @@ impl RttEstimate { max(rtt * 9 / 8, GRANULARITY) } - pub fn first_sample_time(&self) -> Option { + pub const fn first_sample_time(&self) -> Option { self.first_sample_time } #[cfg(test)] - pub fn latest(&self) -> Duration { + pub const fn latest(&self) -> Duration { self.latest_rtt } - pub fn rttvar(&self) -> Duration { + pub const fn rttvar(&self) -> Duration { self.rttvar } - pub fn minimum(&self) -> Duration { + pub const fn minimum(&self) -> Duration { self.min_rtt } diff --git a/neqo-transport/src/send_stream.rs b/neqo-transport/src/send_stream.rs index e443edc033..cf21ff9fa8 100644 --- a/neqo-transport/src/send_stream.rs +++ b/neqo-transport/src/send_stream.rs @@ -138,7 +138,7 @@ enum RangeState { /// Track ranges in the stream as sent or acked. Acked implies sent. Not in a /// range implies needing-to-be-sent, either initially or as a retransmission. -#[derive(Debug, Default, PartialEq)] +#[derive(Debug, Default, PartialEq, Eq)] pub struct RangeTracker { /// The number of bytes that have been acknowledged starting from offset 0. acked: u64, @@ -157,7 +157,7 @@ impl RangeTracker { .map_or(self.acked, |(&k, &(v, _))| k + v) } - fn acked_from_zero(&self) -> u64 { + const fn acked_from_zero(&self) -> u64 { self.acked } @@ -480,7 +480,7 @@ impl RangeTracker { } /// Buffer to contain queued bytes and track their state. -#[derive(Debug, Default, PartialEq)] +#[derive(Debug, Default, PartialEq, Eq)] pub struct TxBuffer { send_buf: VecDeque, // buffer of not-acked bytes ranges: RangeTracker, // ranges in buffer that have been sent or acked @@ -522,12 +522,9 @@ impl TxBuffer { &self.send_buf.as_slices().1[buff_off - self.send_buf.as_slices().0.len()..] }; - let len = if let Some(range_len) = maybe_len { - // Truncate if range crosses deque slices + let len = maybe_len.map_or(slc.len(), |range_len| { min(usize::try_from(range_len).unwrap(), slc.len()) - } else { - slc.len() - }; + }); debug_assert!(len > 0); debug_assert!(len <= slc.len()); @@ -564,7 +561,7 @@ impl TxBuffer { } #[must_use] - pub fn retired(&self) -> u64 { + pub const fn retired(&self) -> u64 { self.ranges.acked_from_zero() } @@ -583,7 +580,7 @@ impl TxBuffer { /// QUIC sending stream states, based on -transport 3.1. #[derive(Debug)] -pub(crate) enum SendStreamState { +pub enum SendStreamState { Ready { fc: SenderFlowControl, conn_fc: Rc>>, @@ -637,7 +634,7 @@ impl SendStreamState { } } - fn name(&self) -> &str { + const fn name(&self) -> &str { match self { Self::Ready { .. } => "Ready", Self::Send { .. } => "Send", @@ -675,7 +672,7 @@ pub struct SendStreamStats { impl SendStreamStats { #[must_use] - pub fn new(bytes_written: u64, bytes_sent: u64, bytes_acked: u64) -> Self { + pub const fn new(bytes_written: u64, bytes_sent: u64, bytes_acked: u64) -> Self { Self { bytes_written, bytes_sent, @@ -684,17 +681,17 @@ impl SendStreamStats { } #[must_use] - pub fn bytes_written(&self) -> u64 { + pub const fn bytes_written(&self) -> u64 { self.bytes_written } #[must_use] - pub fn bytes_sent(&self) -> u64 { + pub const fn bytes_sent(&self) -> u64 { self.bytes_sent } #[must_use] - pub fn bytes_acked(&self) -> u64 { + pub const fn bytes_acked(&self) -> u64 { self.bytes_acked } } @@ -796,7 +793,7 @@ impl SendStream { } #[must_use] - pub fn is_fair(&self) -> bool { + pub const fn is_fair(&self) -> bool { self.fair } @@ -810,7 +807,7 @@ impl SendStream { } #[must_use] - pub fn sendorder(&self) -> Option { + pub const fn sendorder(&self) -> Option { self.sendorder } @@ -858,7 +855,7 @@ impl SendStream { } #[must_use] - pub fn bytes_acked(&self) -> u64 { + pub const fn bytes_acked(&self) -> u64 { match &self.state { SendStreamState::Send { send_buf, .. } | SendStreamState::DataSent { send_buf, .. } => { send_buf.retired() @@ -1227,7 +1224,7 @@ impl SendStream { } #[must_use] - pub fn is_terminal(&self) -> bool { + pub const fn is_terminal(&self) -> bool { matches!( self.state, SendStreamState::DataRecvd { .. } | SendStreamState::ResetRecvd { .. } @@ -1381,11 +1378,7 @@ impl SendStream { &mut self.state } - pub(crate) fn maybe_emit_writable_event( - &mut self, - previous_limit: usize, - current_limit: usize, - ) { + pub(crate) fn maybe_emit_writable_event(&self, previous_limit: usize, current_limit: usize) { let low_watermark = self.writable_event_low_watermark.get(); // Skip if: @@ -1450,7 +1443,7 @@ impl OrderGroup { } #[must_use] - pub fn stream_ids(&self) -> &Vec { + pub const fn stream_ids(&self) -> &Vec { &self.vec } @@ -1509,7 +1502,7 @@ impl<'a> Iterator for OrderGroupIter<'a> { } #[derive(Debug, Default)] -pub(crate) struct SendStreams { +pub struct SendStreams { map: IndexMap, // What we really want is a Priority Queue that we can do arbitrary @@ -1545,14 +1538,17 @@ pub(crate) struct SendStreams { } impl SendStreams { + #[allow(clippy::missing_errors_doc)] pub fn get(&self, id: StreamId) -> Res<&SendStream> { self.map.get(&id).ok_or(Error::InvalidStreamId) } + #[allow(clippy::missing_errors_doc)] pub fn get_mut(&mut self, id: StreamId) -> Res<&mut SendStream> { self.map.get_mut(&id).ok_or(Error::InvalidStreamId) } + #[must_use] pub fn exists(&self, id: StreamId) -> bool { self.map.contains_key(&id) } @@ -1569,6 +1565,8 @@ impl SendStreams { } } + #[allow(clippy::missing_panics_doc)] + #[allow(clippy::missing_errors_doc)] pub fn set_sendorder(&mut self, stream_id: StreamId, sendorder: Option) -> Res<()> { self.set_fairness(stream_id, true)?; if let Some(stream) = self.map.get_mut(&stream_id) { @@ -1593,6 +1591,8 @@ impl SendStreams { } } + #[allow(clippy::missing_panics_doc)] + #[allow(clippy::missing_errors_doc)] pub fn set_fairness(&mut self, stream_id: StreamId, make_fair: bool) -> Res<()> { let stream: &mut SendStream = self.map.get_mut(&stream_id).ok_or(Error::InvalidStreamId)?; let was_fair = stream.fair; @@ -1665,6 +1665,7 @@ impl SendStreams { self.regular.clear(); } + #[allow(clippy::missing_panics_doc)] pub fn remove_terminal(&mut self) { self.map.retain(|stream_id, stream| { if stream.is_terminal() { @@ -1756,6 +1757,7 @@ impl SendStreams { } } + #[allow(clippy::missing_panics_doc)] pub fn update_initial_limit(&mut self, remote: &TransportParameters) { for (id, ss) in &mut self.map { let limit = if id.is_bidi() { @@ -1769,6 +1771,7 @@ impl SendStreams { } } +#[allow(clippy::into_iter_without_iter)] impl<'a> IntoIterator for &'a mut SendStreams { type Item = (&'a StreamId, &'a mut SendStream); type IntoIter = indexmap::map::IterMut<'a, StreamId, SendStream>; @@ -2572,7 +2575,7 @@ mod tests { )); } - fn as_stream_token(t: &RecoveryToken) -> &SendStreamRecoveryToken { + const fn as_stream_token(t: &RecoveryToken) -> &SendStreamRecoveryToken { if let RecoveryToken::Stream(StreamRecoveryToken::Stream(rt)) = &t { rt } else { diff --git a/neqo-transport/src/server.rs b/neqo-transport/src/server.rs index c1fe1f120d..e0ce4e8940 100644 --- a/neqo-transport/src/server.rs +++ b/neqo-transport/src/server.rs @@ -220,7 +220,7 @@ impl Server { } /// Set the policy for address validation. - pub fn set_validation(&mut self, v: ValidateAddress) { + pub fn set_validation(&self, v: ValidateAddress) { self.address_validation.borrow_mut().set_validation(v); } @@ -252,12 +252,7 @@ impl Server { self.connections.borrow().get(&cid[..]).cloned() } - fn handle_initial( - &mut self, - initial: InitialDetails, - dgram: &Datagram, - now: Instant, - ) -> Output { + fn handle_initial(&self, initial: InitialDetails, dgram: &Datagram, now: Instant) -> Output { qdebug!([self], "Handle initial"); let res = self .address_validation @@ -289,17 +284,20 @@ impl Server { &token, &initial.dst_cid, ); - if let Ok(p) = packet { - Output::Datagram(Datagram::new( - dgram.destination(), - dgram.source(), - dgram.tos(), - p, - )) - } else { - qerror!([self], "unable to encode retry, dropping packet"); - Output::None - } + packet.map_or_else( + |_| { + qerror!([self], "unable to encode retry, dropping packet"); + Output::None + }, + |p| { + Output::Datagram(Datagram::new( + dgram.destination(), + dgram.source(), + dgram.tos(), + p, + )) + }, + ) } else { qerror!([self], "no connection ID for retry, dropping packet"); Output::None @@ -309,7 +307,7 @@ impl Server { } fn connection_attempt( - &mut self, + &self, initial: InitialDetails, dgram: &Datagram, orig_dcid: Option, @@ -322,70 +320,71 @@ impl Server { let connection = self.connections.borrow().values().find_map(|c| { (c.borrow().active_attempt.as_ref() == Some(&attempt_key)).then(|| Rc::clone(c)) }); - if let Some(c) = connection { - qdebug!( - [self], - "Handle Initial for existing connection attempt {:?}", - attempt_key - ); - c.borrow_mut().process(Some(dgram), now) - } else { - self.accept_connection(&attempt_key, initial, dgram, orig_dcid, now) - } + connection.map_or_else( + || self.accept_connection(&attempt_key, initial, dgram, orig_dcid, now), + |c| { + qdebug!( + [self], + "Handle Initial for existing connection attempt {:?}", + attempt_key + ); + c.borrow_mut().process(Some(dgram), now) + }, + ) } fn create_qlog_trace(&self, odcid: ConnectionIdRef<'_>) -> NeqoQlog { - if let Some(qlog_dir) = &self.qlog_dir { - let mut qlog_path = qlog_dir.clone(); - - qlog_path.push(format!("{odcid}.qlog")); - - // The original DCID is chosen by the client. Using create_new() - // prevents attackers from overwriting existing logs. - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&qlog_path) - { - Ok(f) => { - qinfo!("Qlog output to {}", qlog_path.display()); - - let streamer = QlogStreamer::new( - qlog::QLOG_VERSION.to_string(), - Some("Neqo server qlog".to_string()), - Some("Neqo server qlog".to_string()), - None, - std::time::Instant::now(), - common::qlog::new_trace(Role::Server), - qlog::events::EventImportance::Base, - Box::new(f), - ); - let n_qlog = NeqoQlog::enabled(streamer, qlog_path); - match n_qlog { - Ok(nql) => nql, - Err(e) => { - // Keep going but w/o qlogging - qerror!("NeqoQlog error: {}", e); - NeqoQlog::disabled() + self.qlog_dir + .as_ref() + .map_or_else(NeqoQlog::disabled, |qlog_dir| { + let mut qlog_path = qlog_dir.clone(); + + qlog_path.push(format!("{odcid}.qlog")); + + // The original DCID is chosen by the client. Using create_new() + // prevents attackers from overwriting existing logs. + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&qlog_path) + { + Ok(f) => { + qinfo!("Qlog output to {}", qlog_path.display()); + + let streamer = QlogStreamer::new( + qlog::QLOG_VERSION.to_string(), + Some("Neqo server qlog".to_string()), + Some("Neqo server qlog".to_string()), + None, + std::time::Instant::now(), + common::qlog::new_trace(Role::Server), + qlog::events::EventImportance::Base, + Box::new(f), + ); + let n_qlog = NeqoQlog::enabled(streamer, qlog_path); + match n_qlog { + Ok(nql) => nql, + Err(e) => { + // Keep going but w/o qlogging + qerror!("NeqoQlog error: {}", e); + NeqoQlog::disabled() + } } } + Err(e) => { + qerror!( + "Could not open file {} for qlog output: {}", + qlog_path.display(), + e + ); + NeqoQlog::disabled() + } } - Err(e) => { - qerror!( - "Could not open file {} for qlog output: {}", - qlog_path.display(), - e - ); - NeqoQlog::disabled() - } - } - } else { - NeqoQlog::disabled() - } + }) } fn setup_connection( - &mut self, + &self, c: &mut Connection, attempt_key: &AttemptKey, initial: InitialDetails, @@ -411,7 +410,7 @@ impl Server { } fn accept_connection( - &mut self, + &self, attempt_key: &AttemptKey, initial: InitialDetails, dgram: &Datagram, @@ -452,7 +451,7 @@ impl Server { qwarn!([self], "Unable to create connection"); if e == crate::Error::VersionNegotiation { crate::qlog::server_version_information_failed( - &mut self.create_qlog_trace(attempt_key.odcid.as_cid_ref()), + &self.create_qlog_trace(attempt_key.odcid.as_cid_ref()), self.conn_params.get_versions().all(), initial.version.wire_version(), ); @@ -465,7 +464,7 @@ impl Server { /// Handle 0-RTT packets that were sent with the client's choice of connection ID. /// Most 0-RTT will arrive this way. A client can usually send 1-RTT after it /// receives a connection ID from the server. - fn handle_0rtt(&mut self, dgram: &Datagram, dcid: ConnectionId, now: Instant) -> Output { + fn handle_0rtt(&self, dgram: &Datagram, dcid: ConnectionId, now: Instant) -> Output { let attempt_key = AttemptKey { remote_address: dgram.source(), odcid: dcid, @@ -473,20 +472,23 @@ impl Server { let connection = self.connections.borrow().values().find_map(|c| { (c.borrow().active_attempt.as_ref() == Some(&attempt_key)).then(|| Rc::clone(c)) }); - if let Some(c) = connection { - qdebug!( - [self], - "Handle 0-RTT for existing connection attempt {:?}", - attempt_key - ); - c.borrow_mut().process(Some(dgram), now) - } else { - qdebug!([self], "Dropping 0-RTT for unknown connection"); - Output::None - } + connection.map_or_else( + || { + qdebug!([self], "Dropping 0-RTT for unknown connection"); + Output::None + }, + |c| { + qdebug!( + [self], + "Handle 0-RTT for existing connection attempt {:?}", + attempt_key + ); + c.borrow_mut().process(Some(dgram), now) + }, + ) } - fn process_input(&mut self, dgram: &Datagram, now: Instant) -> Output { + fn process_input(&self, dgram: &Datagram, now: Instant) -> Output { qtrace!("Process datagram: {}", hex(&dgram[..])); // This is only looking at the first packet header in the datagram. @@ -530,7 +532,7 @@ impl Server { ); crate::qlog::server_version_information_failed( - &mut self.create_qlog_trace(packet.dcid()), + &self.create_qlog_trace(packet.dcid()), self.conn_params.get_versions().all(), packet.wire_version(), ); @@ -568,7 +570,7 @@ impl Server { /// Iterate through the pending connections looking for any that might want /// to send a datagram. Stop at the first one that does. - fn process_next_output(&mut self, now: Instant) -> Output { + fn process_next_output(&self, now: Instant) -> Output { let mut callback = None; for connection in self.connections.borrow().values() { @@ -585,7 +587,8 @@ impl Server { callback.map_or(Output::None, Output::Callback) } - pub fn process(&mut self, dgram: Option<&Datagram>, now: Instant) -> Output { + #[must_use] + pub fn process(&self, dgram: Option<&Datagram>, now: Instant) -> Output { let out = dgram .map_or(Output::None, |d| self.process_input(d, now)) .or_else(|| self.process_next_output(now)); @@ -600,10 +603,10 @@ impl Server { /// This lists the connections that have received new events /// as a result of calling `process()`. - // // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable types. #[allow(clippy::mutable_key_type)] - pub fn active_connections(&mut self) -> HashSet { + #[must_use] + pub fn active_connections(&self) -> HashSet { self.connections .borrow() .values() @@ -634,7 +637,8 @@ impl ActiveConnectionRef { std::cell::Ref::map(self.c.borrow(), |c| &c.c) } - pub fn borrow_mut(&mut self) -> impl DerefMut + '_ { + #[must_use] + pub fn borrow_mut(&self) -> impl DerefMut + '_ { std::cell::RefMut::map(self.c.borrow_mut(), |c| &mut c.c) } @@ -676,7 +680,7 @@ impl ServerConnectionIdGenerator { self.c = Rc::downgrade(c); } - fn insert_cid(&mut self, cid: ConnectionId, rc: StateRef) { + fn insert_cid(&self, cid: ConnectionId, rc: StateRef) { debug_assert!(!cid.is_empty()); self.connections.borrow_mut().insert(cid, rc); } diff --git a/neqo-transport/src/stats.rs b/neqo-transport/src/stats.rs index 0a61097010..0c4b604671 100644 --- a/neqo-transport/src/stats.rs +++ b/neqo-transport/src/stats.rs @@ -18,7 +18,7 @@ use neqo_common::qwarn; use crate::packet::PacketNumber; -pub(crate) const MAX_PTO_COUNTS: usize = 16; +pub const MAX_PTO_COUNTS: usize = 16; #[derive(Default, Clone)] #[cfg_attr(test, derive(PartialEq, Eq))] diff --git a/neqo-transport/src/stream_id.rs b/neqo-transport/src/stream_id.rs index 8dbe2dcfbc..afd4bd8a36 100644 --- a/neqo-transport/src/stream_id.rs +++ b/neqo-transport/src/stream_id.rs @@ -8,9 +8,8 @@ use neqo_common::Role; -#[derive(PartialEq, Debug, Copy, Clone, PartialOrd, Eq, Ord, Hash)] - /// The type of stream, either Bi-Directional or Uni-Directional. +#[derive(PartialEq, Debug, Copy, Clone, PartialOrd, Eq, Ord, Hash)] pub enum StreamType { BiDi, UniDi, @@ -26,7 +25,7 @@ impl StreamId { } #[must_use] - pub fn init(stream_type: StreamType, role: Role) -> Self { + pub const fn init(stream_type: StreamType, role: Role) -> Self { let type_val = match stream_type { StreamType::BiDi => 0, StreamType::UniDi => 2, @@ -35,22 +34,22 @@ impl StreamId { } #[must_use] - pub fn as_u64(self) -> u64 { + pub const fn as_u64(self) -> u64 { self.0 } #[must_use] - pub fn is_bidi(self) -> bool { + pub const fn is_bidi(self) -> bool { self.as_u64() & 0x02 == 0 } #[must_use] - pub fn is_uni(self) -> bool { + pub const fn is_uni(self) -> bool { !self.is_bidi() } #[must_use] - pub fn stream_type(self) -> StreamType { + pub const fn stream_type(self) -> StreamType { if self.is_bidi() { StreamType::BiDi } else { @@ -59,17 +58,17 @@ impl StreamId { } #[must_use] - pub fn is_client_initiated(self) -> bool { + pub const fn is_client_initiated(self) -> bool { self.as_u64() & 0x01 == 0 } #[must_use] - pub fn is_server_initiated(self) -> bool { + pub const fn is_server_initiated(self) -> bool { !self.is_client_initiated() } #[must_use] - pub fn role(self) -> Role { + pub const fn role(self) -> Role { if self.is_client_initiated() { Role::Client } else { @@ -78,7 +77,7 @@ impl StreamId { } #[must_use] - pub fn is_self_initiated(self, my_role: Role) -> bool { + pub const fn is_self_initiated(self, my_role: Role) -> bool { match my_role { Role::Client if self.is_client_initiated() => true, Role::Server if self.is_server_initiated() => true, @@ -87,17 +86,17 @@ impl StreamId { } #[must_use] - pub fn is_remote_initiated(self, my_role: Role) -> bool { + pub const fn is_remote_initiated(self, my_role: Role) -> bool { !self.is_self_initiated(my_role) } #[must_use] - pub fn is_send_only(self, my_role: Role) -> bool { + pub const fn is_send_only(self, my_role: Role) -> bool { self.is_uni() && self.is_self_initiated(my_role) } #[must_use] - pub fn is_recv_only(self, my_role: Role) -> bool { + pub const fn is_recv_only(self, my_role: Role) -> bool { self.is_uni() && self.is_remote_initiated(my_role) } @@ -107,7 +106,7 @@ impl StreamId { /// This returns a bit that is shared by all streams created by this role. #[must_use] - pub fn role_bit(role: Role) -> u64 { + pub const fn role_bit(role: Role) -> u64 { match role { Role::Server => 1, Role::Client => 0, diff --git a/neqo-transport/src/streams.rs b/neqo-transport/src/streams.rs index b95b33c294..ba8a886fc2 100644 --- a/neqo-transport/src/streams.rs +++ b/neqo-transport/src/streams.rs @@ -486,7 +486,7 @@ impl Streams { } } - pub fn handle_data_blocked(&mut self) { + pub fn handle_data_blocked(&self) { self.receiver_fc.borrow_mut().send_flowc_update(); } @@ -559,7 +559,8 @@ impl Streams { self.recv.keep_alive(stream_id, keep) } - pub fn need_keep_alive(&mut self) -> bool { + #[must_use] + pub fn need_keep_alive(&self) -> bool { self.recv.need_keep_alive() } } diff --git a/neqo-transport/src/tparams.rs b/neqo-transport/src/tparams.rs index 5161b69d6b..4b83533e3c 100644 --- a/neqo-transport/src/tparams.rs +++ b/neqo-transport/src/tparams.rs @@ -111,11 +111,11 @@ impl PreferredAddress { } #[must_use] - pub fn ipv4(&self) -> Option { + pub const fn ipv4(&self) -> Option { self.v4 } #[must_use] - pub fn ipv6(&self) -> Option { + pub const fn ipv6(&self) -> Option { self.v6 } } @@ -516,8 +516,10 @@ impl TransportParameters { ) { continue; } - let ok = if let Some(v_self) = self.params.get(k) { - match (v_self, v_rem) { + let ok = self + .params + .get(k) + .map_or(false, |v_self| match (v_self, v_rem) { (TransportParameter::Integer(i_self), TransportParameter::Integer(i_rem)) => { if *k == MIN_ACK_DELAY { // MIN_ACK_DELAY is backwards: @@ -535,10 +537,7 @@ impl TransportParameters { TransportParameter::Versions { current: v_rem, .. }, ) => v_self == v_rem, _ => false, - } - } else { - false - }; + }); if !ok { return false; } @@ -623,7 +622,7 @@ impl TransportParametersHandler { /// Get the version as set (or as determined by a compatible upgrade). #[must_use] - pub fn version(&self) -> Version { + pub const fn version(&self) -> Version { self.versions.initial() } diff --git a/neqo-transport/src/tracking.rs b/neqo-transport/src/tracking.rs index 7c97b55f27..90bbd0b54a 100644 --- a/neqo-transport/src/tracking.rs +++ b/neqo-transport/src/tracking.rs @@ -56,6 +56,7 @@ impl From for PacketNumberSpace { } } +#[allow(clippy::fallible_impl_from)] impl From for PacketNumberSpace { fn from(pt: PacketType) -> Self { match pt { @@ -75,7 +76,7 @@ pub struct PacketNumberSpaceSet { } impl PacketNumberSpaceSet { - pub fn all() -> Self { + pub const fn all() -> Self { Self { initial: true, handshake: true, @@ -159,7 +160,7 @@ pub struct PacketRange { impl PacketRange { /// Make a single packet range. - pub fn new(pn: PacketNumber) -> Self { + pub const fn new(pn: PacketNumber) -> Self { Self { largest: pn, smallest: pn, @@ -168,17 +169,17 @@ impl PacketRange { } /// Get the number of acknowleged packets in the range. - pub fn len(&self) -> u64 { + pub const fn len(&self) -> u64 { self.largest - self.smallest + 1 } /// Returns whether this needs to be sent. - pub fn ack_needed(&self) -> bool { + pub const fn ack_needed(&self) -> bool { self.ack_needed } /// Return whether the given number is in the range. - pub fn contains(&self, pn: PacketNumber) -> bool { + pub const fn contains(&self, pn: PacketNumber) -> bool { (pn >= self.smallest) && (pn <= self.largest) } @@ -301,7 +302,7 @@ impl RecvdPackets { } /// Get the time at which the next ACK should be sent. - pub fn ack_time(&self) -> Option { + pub const fn ack_time(&self) -> Option { self.ack_time } @@ -481,9 +482,7 @@ impl RecvdPackets { // When congestion limited, ACK-only packets are 255 bytes at most // (`recovery::ACK_ONLY_SIZE_LIMIT - 1`). This results in limiting the // ranges to 13 here. - let max_ranges = if let Some(avail) = builder - .remaining() - .checked_sub(RecvdPackets::USEFUL_ACK_LEN) + let max_ranges = if let Some(avail) = builder.remaining().checked_sub(Self::USEFUL_ACK_LEN) { // Apply a hard maximum to keep plenty of space for other stuff. min(1 + (avail / 16), MAX_ACKS_PER_FRAME) diff --git a/neqo-transport/src/version.rs b/neqo-transport/src/version.rs index eee598fdd0..2aee6b9aca 100644 --- a/neqo-transport/src/version.rs +++ b/neqo-transport/src/version.rs @@ -34,7 +34,7 @@ impl Version { } } - pub(crate) fn initial_salt(self) -> &'static [u8] { + pub(crate) const fn initial_salt(self) -> &'static [u8] { const INITIAL_SALT_V2: &[u8] = &[ 0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26, 0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9, @@ -54,7 +54,7 @@ impl Version { } } - pub(crate) fn label_prefix(self) -> &'static str { + pub(crate) const fn label_prefix(self) -> &'static str { match self { Self::Version2 => "quicv2 ", Self::Version1 | Self::Draft29 | Self::Draft30 | Self::Draft31 | Self::Draft32 => { @@ -63,7 +63,7 @@ impl Version { } } - pub(crate) fn retry_secret(self) -> &'static [u8] { + pub(crate) const fn retry_secret(self) -> &'static [u8] { const RETRY_SECRET_V2: &[u8] = &[ 0xc4, 0xdd, 0x24, 0x84, 0xd6, 0x81, 0xae, 0xfa, 0x4f, 0xf4, 0xd6, 0x9c, 0x2c, 0x20, 0x29, 0x99, 0x84, 0xa7, 0x65, 0xa5, 0xd3, 0xc3, 0x19, 0x82, 0xf3, 0x8f, 0xc7, 0x41, @@ -86,7 +86,7 @@ impl Version { } } - pub(crate) fn is_draft(self) -> bool { + pub(crate) const fn is_draft(self) -> bool { matches!( self, Self::Draft29 | Self::Draft30 | Self::Draft31 | Self::Draft32, @@ -181,7 +181,7 @@ impl VersionConfig { } #[must_use] - pub fn initial(&self) -> Version { + pub const fn initial(&self) -> Version { self.initial } diff --git a/neqo-transport/tests/common/mod.rs b/neqo-transport/tests/common/mod.rs index 2e28fc3070..e149379f34 100644 --- a/neqo-transport/tests/common/mod.rs +++ b/neqo-transport/tests/common/mod.rs @@ -41,7 +41,9 @@ pub fn default_server() -> Server { } // Check that there is at least one connection. Returns a ref to the first confirmed connection. -pub fn connected_server(server: &mut Server) -> ActiveConnectionRef { +pub fn connected_server(server: &Server) -> ActiveConnectionRef { + // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable types. + #[allow(clippy::mutable_key_type)] let server_connections = server.active_connections(); // Find confirmed connections. There should only be one. let mut confirmed = server_connections @@ -52,7 +54,7 @@ pub fn connected_server(server: &mut Server) -> ActiveConnectionRef { } /// Connect. This returns a reference to the server connection. -pub fn connect(client: &mut Connection, server: &mut Server) -> ActiveConnectionRef { +pub fn connect(client: &mut Connection, server: &Server) -> ActiveConnectionRef { server.set_validation(ValidateAddress::Never); assert_eq!(*client.state(), State::Init); @@ -98,7 +100,7 @@ pub fn find_ticket(client: &mut Connection) -> ResumptionToken { } /// Connect to the server and have it generate a ticket. -pub fn generate_ticket(server: &mut Server) -> ResumptionToken { +pub fn generate_ticket(server: &Server) -> ResumptionToken { let mut client = default_client(); let mut server_conn = connect(&mut client, server); diff --git a/neqo-transport/tests/retry.rs b/neqo-transport/tests/retry.rs index 5f8d0f5700..65077e0764 100644 --- a/neqo-transport/tests/retry.rs +++ b/neqo-transport/tests/retry.rs @@ -31,7 +31,7 @@ use test_fixture::{ #[test] fn retry_basic() { - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut client = default_client(); @@ -53,7 +53,7 @@ fn retry_basic() { assert_eq!(*client.state(), State::Connected); let dgram = server.process(dgram.as_ref(), now()).dgram(); // (done) assert!(dgram.is_some()); // Note that this packet will be dropped... - connected_server(&mut server); + connected_server(&server); } /// Receiving a Retry is enough to infer something about the RTT. @@ -61,7 +61,7 @@ fn retry_basic() { #[test] fn implicit_rtt_retry() { const RTT: Duration = Duration::from_secs(2); - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut client = default_client(); let mut now = now(); @@ -78,7 +78,7 @@ fn implicit_rtt_retry() { #[test] fn retry_expired() { - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut client = default_client(); let mut now = now(); @@ -101,8 +101,8 @@ fn retry_expired() { // Attempt a retry with 0-RTT, and have 0-RTT packets sent with the second ClientHello. #[test] fn retry_0rtt() { - let mut server = default_server(); - let token = generate_ticket(&mut server); + let server = default_server(); + let token = generate_ticket(&server); server.set_validation(ValidateAddress::Always); let mut client = default_client(); @@ -132,13 +132,13 @@ fn retry_0rtt() { assert_eq!(*client.state(), State::Connected); let dgram = server.process(dgram.as_ref(), now()).dgram(); // (done) assert!(dgram.is_some()); - connected_server(&mut server); + connected_server(&server); assert!(client.tls_info().unwrap().resumed()); } #[test] fn retry_different_ip() { - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut client = default_client(); @@ -163,8 +163,8 @@ fn retry_different_ip() { #[test] fn new_token_different_ip() { - let mut server = default_server(); - let token = generate_ticket(&mut server); + let server = default_server(); + let token = generate_ticket(&server); server.set_validation(ValidateAddress::NoToken); let mut client = default_client(); @@ -185,8 +185,8 @@ fn new_token_different_ip() { #[test] fn new_token_expired() { - let mut server = default_server(); - let token = generate_ticket(&mut server); + let server = default_server(); + let token = generate_ticket(&server); server.set_validation(ValidateAddress::NoToken); let mut client = default_client(); @@ -210,8 +210,8 @@ fn new_token_expired() { #[test] fn retry_after_initial() { - let mut server = default_server(); - let mut retry_server = default_server(); + let server = default_server(); + let retry_server = default_server(); retry_server.set_validation(ValidateAddress::Always); let mut client = default_client(); @@ -244,12 +244,12 @@ fn retry_after_initial() { assert_eq!(*client.state(), State::Connected); let dgram = server.process(dgram.as_ref(), now()).dgram(); // (done) assert!(dgram.is_some()); - connected_server(&mut server); + connected_server(&server); } #[test] fn retry_bad_integrity() { - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut client = default_client(); @@ -273,9 +273,9 @@ fn retry_bad_integrity() { #[test] fn retry_bad_token() { let mut client = default_client(); - let mut retry_server = default_server(); + let retry_server = default_server(); retry_server.set_validation(ValidateAddress::Always); - let mut server = default_server(); + let server = default_server(); // Send a retry to one server, then replay it to the other. let client_initial1 = client.process(None, now()).dgram(); @@ -299,7 +299,7 @@ fn retry_bad_token() { #[test] fn retry_after_pto() { let mut client = default_client(); - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut now = now(); @@ -322,7 +322,7 @@ fn retry_after_pto() { #[test] fn vn_after_retry() { - let mut server = default_server(); + let server = default_server(); server.set_validation(ValidateAddress::Always); let mut client = default_client(); @@ -364,9 +364,9 @@ fn vn_after_retry() { #[allow(clippy::shadow_unrelated)] fn mitm_retry() { let mut client = default_client(); - let mut retry_server = default_server(); + let retry_server = default_server(); retry_server.set_validation(ValidateAddress::Always); - let mut server = default_server(); + let server = default_server(); // Trigger initial and a second client Initial. let client_initial1 = client.process(None, now()).dgram(); diff --git a/neqo-transport/tests/server.rs b/neqo-transport/tests/server.rs index 0ce90faba2..8740697dd8 100644 --- a/neqo-transport/tests/server.rs +++ b/neqo-transport/tests/server.rs @@ -36,7 +36,7 @@ use test_fixture::{ /// Only when the connection fails. pub fn complete_connection( client: &mut Connection, - server: &mut Server, + server: &Server, mut datagram: Option, ) -> ActiveConnectionRef { let is_done = |c: &Connection| { @@ -58,19 +58,19 @@ pub fn complete_connection( #[test] fn single_client() { - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); - connect(&mut client, &mut server); + connect(&mut client, &server); } #[test] fn connect_single_version_both() { fn connect_one_version(version: Version) { let params = ConnectionParameters::default().versions(version, vec![version]); - let mut server = new_server(params.clone()); + let server = new_server(params.clone()); let mut client = new_client(params); - let server_conn = connect(&mut client, &mut server); + let server_conn = connect(&mut client, &server); assert_eq!(client.version(), version); assert_eq!(server_conn.borrow().version(), version); } @@ -84,11 +84,11 @@ fn connect_single_version_both() { #[test] fn connect_single_version_client() { fn connect_one_version(version: Version) { - let mut server = default_server(); + let server = default_server(); let mut client = new_client(ConnectionParameters::default().versions(version, vec![version])); - let server_conn = connect(&mut client, &mut server); + let server_conn = connect(&mut client, &server); assert_eq!(client.version(), version); assert_eq!(server_conn.borrow().version(), version); } @@ -102,8 +102,7 @@ fn connect_single_version_client() { #[test] fn connect_single_version_server() { fn connect_one_version(version: Version) { - let mut server = - new_server(ConnectionParameters::default().versions(version, vec![version])); + let server = new_server(ConnectionParameters::default().versions(version, vec![version])); let mut client = default_client(); @@ -116,7 +115,7 @@ fn connect_single_version_server() { client.process_input(&dgram.unwrap(), now()); } - let server_conn = connect(&mut client, &mut server); + let server_conn = connect(&mut client, &server); assert_eq!(client.version(), version); assert_eq!(server_conn.borrow().version(), version); } @@ -129,7 +128,7 @@ fn connect_single_version_server() { #[test] fn duplicate_initial() { - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); assert_eq!(*client.state(), State::Init); @@ -144,12 +143,12 @@ fn duplicate_initial() { assert!(dgram.is_none()); assert_eq!(server.active_connections().len(), 1); - complete_connection(&mut client, &mut server, server_initial); + complete_connection(&mut client, &server, server_initial); } #[test] fn duplicate_initial_new_path() { - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); assert_eq!(*client.state(), State::Init); @@ -169,12 +168,12 @@ fn duplicate_initial_new_path() { assert!(server_initial.is_some()); assert_eq!(server.active_connections().len(), 2); - complete_connection(&mut client, &mut server, server_initial); + complete_connection(&mut client, &server, server_initial); } #[test] fn different_initials_same_path() { - let mut server = default_server(); + let server = default_server(); let mut client1 = default_client(); let mut client2 = default_client(); @@ -195,13 +194,13 @@ fn different_initials_same_path() { assert!(server_initial2.is_some()); assert_eq!(server.active_connections().len(), 2); - complete_connection(&mut client1, &mut server, server_initial1); - complete_connection(&mut client2, &mut server, server_initial2); + complete_connection(&mut client1, &server, server_initial1); + complete_connection(&mut client2, &server, server_initial2); } #[test] fn same_initial_after_connected() { - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); let client_initial = client.process(None, now()); @@ -209,7 +208,7 @@ fn same_initial_after_connected() { let server_initial = server.process(client_initial.as_dgram_ref(), now()).dgram(); assert!(server_initial.is_some()); - complete_connection(&mut client, &mut server, server_initial); + complete_connection(&mut client, &server, server_initial); assert_eq!(server.active_connections().len(), 1); // Now make a new connection using the exact same initial as before. @@ -223,7 +222,7 @@ fn same_initial_after_connected() { #[test] fn drop_non_initial() { const CID: &[u8] = &[55; 8]; // not a real connection ID - let mut server = default_server(); + let server = default_server(); // This is big enough to look like an Initial, but it uses the Retry type. let mut header = neqo_common::Encoder::with_capacity(MIN_INITIAL_PACKET_SIZE); @@ -242,7 +241,7 @@ fn drop_non_initial() { #[test] fn drop_short_initial() { const CID: &[u8] = &[55; 8]; // not a real connection ID - let mut server = default_server(); + let server = default_server(); // This too small to be an Initial, but it is otherwise plausible. let mut header = neqo_common::Encoder::with_capacity(1199); @@ -261,7 +260,7 @@ fn drop_short_initial() { #[test] fn drop_short_header_packet_for_unknown_connection() { const CID: &[u8] = &[55; 8]; // not a real connection ID - let mut server = default_server(); + let server = default_server(); let mut header = neqo_common::Encoder::with_capacity(MIN_INITIAL_PACKET_SIZE); header @@ -281,8 +280,8 @@ fn drop_short_header_packet_for_unknown_connection() { /// the handshake is running. #[test] fn zero_rtt() { - let mut server = default_server(); - let token = generate_ticket(&mut server); + let server = default_server(); + let token = generate_ticket(&server); // Discharge the old connection so that we don't have to worry about it. let mut now = now(); @@ -324,6 +323,8 @@ fn zero_rtt() { let shs = server.process(Some(&c1), now); mem::drop(server.process(Some(&c3), now)); // The server will have received two STREAM frames now if it processed both packets. + // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable types. + #[allow(clippy::mutable_key_type)] let active = server.active_connections(); assert_eq!(active.len(), 1); assert_eq!( @@ -346,6 +347,8 @@ fn zero_rtt() { // The server will drop this last 0-RTT packet. mem::drop(server.process(Some(&c4), now)); + // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable types. + #[allow(clippy::mutable_key_type)] let active = server.active_connections(); assert_eq!(active.len(), 1); assert_eq!( @@ -363,8 +366,8 @@ fn zero_rtt() { #[test] fn new_token_0rtt() { - let mut server = default_server(); - let token = generate_ticket(&mut server); + let server = default_server(); + let token = generate_ticket(&server); server.set_validation(ValidateAddress::NoToken); let mut client = default_client(); @@ -388,14 +391,14 @@ fn new_token_0rtt() { assert_eq!(*client.state(), State::Connected); let dgram = server.process(dgram.as_dgram_ref(), now()); // (done) assert!(dgram.as_dgram_ref().is_some()); - connected_server(&mut server); + connected_server(&server); assert!(client.tls_info().unwrap().resumed()); } #[test] fn new_token_different_port() { - let mut server = default_server(); - let token = generate_ticket(&mut server); + let server = default_server(); + let token = generate_ticket(&server); server.set_validation(ValidateAddress::NoToken); let mut client = default_client(); @@ -417,7 +420,7 @@ fn new_token_different_port() { #[test] fn bad_client_initial() { let mut client = default_client(); - let mut server = default_server(); + let server = default_server(); let dgram = client.process(None, now()).dgram().expect("a datagram"); let (header, d_cid, s_cid, payload) = decode_initial_header(&dgram, Role::Client).unwrap(); @@ -505,7 +508,7 @@ fn bad_client_initial() { #[test] fn bad_client_initial_connection_close() { let mut client = default_client(); - let mut server = default_server(); + let server = default_server(); let dgram = client.process(None, now()).dgram().expect("a datagram"); let (header, d_cid, s_cid, payload) = decode_initial_header(&dgram, Role::Client).unwrap(); @@ -557,7 +560,7 @@ fn bad_client_initial_connection_close() { #[test] fn version_negotiation_ignored() { - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); // Any packet will do, but let's make something that looks real. @@ -604,8 +607,7 @@ fn version_negotiation() { assert_ne!(VN_VERSION, Version::default()); assert!(!Version::default().is_compatible(VN_VERSION)); - let mut server = - new_server(ConnectionParameters::default().versions(VN_VERSION, vec![VN_VERSION])); + let server = new_server(ConnectionParameters::default().versions(VN_VERSION, vec![VN_VERSION])); let mut client = default_client(); // `connect()` runs a fixed exchange, so manually run the Version Negotiation. @@ -615,7 +617,7 @@ fn version_negotiation() { assertions::assert_vn(dgram.as_ref().unwrap()); client.process_input(&dgram.unwrap(), now()); - let sconn = connect(&mut client, &mut server); + let sconn = connect(&mut client, &server); assert_eq!(client.version(), VN_VERSION); assert_eq!(sconn.borrow().version(), VN_VERSION); } @@ -631,7 +633,7 @@ fn version_negotiation_and_compatible() { assert!(!ORIG_VERSION.is_compatible(COMPAT_VERSION)); assert!(VN_VERSION.is_compatible(COMPAT_VERSION)); - let mut server = new_server( + let server = new_server( ConnectionParameters::default().versions(VN_VERSION, vec![COMPAT_VERSION, VN_VERSION]), ); // Note that the order of versions at the client only determines what it tries first. @@ -665,7 +667,7 @@ fn version_negotiation_and_compatible() { client.process_input(&dgram.unwrap(), now()); assert_eq!(*client.state(), State::Confirmed); - let sconn = connected_server(&mut server); + let sconn = connected_server(&server); assert_eq!(client.version(), COMPAT_VERSION); assert_eq!(sconn.borrow().version(), COMPAT_VERSION); } @@ -688,8 +690,8 @@ fn compatible_upgrade_resumption_and_vn() { let mut client = new_client(client_params.clone()); assert_eq!(client.version(), ORIG_VERSION); - let mut server = default_server(); - let mut server_conn = connect(&mut client, &mut server); + let server = default_server(); + let server_conn = connect(&mut client, &server); assert_eq!(client.version(), COMPAT_VERSION); assert_eq!(server_conn.borrow().version(), COMPAT_VERSION); @@ -700,7 +702,7 @@ fn compatible_upgrade_resumption_and_vn() { // This new server will reject the ticket, but it will also generate a VN packet. let mut client = new_client(client_params); - let mut server = new_server( + let server = new_server( ConnectionParameters::default().versions(RESUMPTION_VERSION, vec![RESUMPTION_VERSION]), ); client.enable_resumption(now(), ticket).unwrap(); @@ -713,7 +715,7 @@ fn compatible_upgrade_resumption_and_vn() { assertions::assert_vn(dgram.as_ref().unwrap()); client.process_input(&dgram.unwrap(), now()); - let server_conn = connect(&mut client, &mut server); + let server_conn = connect(&mut client, &server); assert_eq!(client.version(), RESUMPTION_VERSION); assert_eq!(server_conn.borrow().version(), RESUMPTION_VERSION); } @@ -721,9 +723,9 @@ fn compatible_upgrade_resumption_and_vn() { #[test] fn closed() { // Let a server connection idle and it should be removed. - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); - connect(&mut client, &mut server); + connect(&mut client, &server); // The server will have sent a few things, so it will be on PTO. let res = server.process(None, now()); @@ -747,7 +749,7 @@ fn can_create_streams(c: &mut Connection, t: StreamType, n: u64) { #[test] fn max_streams() { const MAX_STREAMS: u64 = 40; - let mut server = Server::new( + let server = Server::new( now(), test_fixture::DEFAULT_KEYS, test_fixture::DEFAULT_ALPN, @@ -761,7 +763,7 @@ fn max_streams() { .expect("should create a server"); let mut client = default_client(); - connect(&mut client, &mut server); + connect(&mut client, &server); // Make sure that we can create MAX_STREAMS uni- and bidirectional streams. can_create_streams(&mut client, StreamType::UniDi, MAX_STREAMS); @@ -770,7 +772,7 @@ fn max_streams() { #[test] fn max_streams_default() { - let mut server = Server::new( + let server = Server::new( now(), test_fixture::DEFAULT_KEYS, test_fixture::DEFAULT_ALPN, @@ -782,7 +784,7 @@ fn max_streams_default() { .expect("should create a server"); let mut client = default_client(); - connect(&mut client, &mut server); + connect(&mut client, &server); // Make sure that we can create streams up to the local limit. let local_limit_unidi = ConnectionParameters::default().get_max_streams(StreamType::UniDi); @@ -803,7 +805,7 @@ impl ZeroRttChecker for RejectZeroRtt { fn max_streams_after_0rtt_rejection() { const MAX_STREAMS_BIDI: u64 = 40; const MAX_STREAMS_UNIDI: u64 = 30; - let mut server = Server::new( + let server = Server::new( now(), test_fixture::DEFAULT_KEYS, test_fixture::DEFAULT_ALPN, @@ -815,7 +817,7 @@ fn max_streams_after_0rtt_rejection() { .max_streams(StreamType::UniDi, MAX_STREAMS_UNIDI), ) .expect("should create a server"); - let token = generate_ticket(&mut server); + let token = generate_ticket(&server); let mut client = default_client(); client.enable_resumption(now(), &token).unwrap(); @@ -839,7 +841,7 @@ fn ech() { let mut client = default_client(); client.client_enable_ech(server.ech_config()).unwrap(); - let server_instance = connect(&mut client, &mut server); + let server_instance = connect(&mut client, &server); assert!(client.tls_info().unwrap().ech_accepted()); assert!(server_instance.borrow().tls_info().unwrap().ech_accepted()); @@ -854,13 +856,13 @@ fn ech() { #[test] fn has_active_connections() { - let mut server = default_server(); + let server = default_server(); let mut client = default_client(); assert!(!server.has_active_connections()); let initial = client.process(None, now()); - let _ = server.process(initial.as_dgram_ref(), now()).dgram(); + _ = server.process(initial.as_dgram_ref(), now()).dgram(); assert!(server.has_active_connections()); } diff --git a/neqo-udp/Cargo.toml b/neqo-udp/Cargo.toml index a93de8be60..b604912cb9 100644 --- a/neqo-udp/Cargo.toml +++ b/neqo-udp/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/neqo-udp/src/lib.rs b/neqo-udp/src/lib.rs index 46bb396933..a356810213 100644 --- a/neqo-udp/src/lib.rs +++ b/neqo-udp/src/lib.rs @@ -126,7 +126,7 @@ impl Socket { /// Receive a batch of [`Datagram`]s on the given [`Socket`], each set with /// the provided local address. - pub fn recv(&mut self, local_address: &SocketAddr) -> Result, io::Error> { + pub fn recv(&self, local_address: &SocketAddr) -> Result, io::Error> { Self::recv_inner(local_address, &self.state, (&self.inner).into()) } } @@ -167,7 +167,7 @@ impl Socket { /// Receive a batch of [`Datagram`]s on the given [`Socket`], each set with /// the provided local address. - pub fn recv(&mut self, local_address: &SocketAddr) -> Result, io::Error> { + pub fn recv(&self, local_address: &SocketAddr) -> Result, io::Error> { self.inner .try_io(tokio::io::Interest::READABLE, || { Self::recv_inner(local_address, &self.state, (&self.inner).into()) @@ -193,13 +193,13 @@ mod tests { async fn datagram_tos() -> Result<(), io::Error> { let sender = Socket::bind("127.0.0.1:0")?; let receiver_addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let mut receiver = Socket::bind(receiver_addr)?; + let receiver = Socket::bind(receiver_addr)?; let datagram = Datagram::new( sender.local_addr()?, receiver.local_addr()?, IpTos::from((IpTosDscp::Le, IpTosEcn::Ect1)), - "Hello, world!".as_bytes().to_vec(), + b"Hello, world!".to_vec(), ); sender.writable().await?; @@ -230,7 +230,7 @@ mod tests { let sender = Socket::bind("127.0.0.1:0")?; let receiver_addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let mut receiver = Socket::bind(receiver_addr)?; + let receiver = Socket::bind(receiver_addr)?; // `neqo_common::udp::Socket::send` does not yet // (https://github.com/mozilla/neqo/issues/1693) support GSO. Use diff --git a/test-fixture/Cargo.toml b/test-fixture/Cargo.toml index 3e5e797e4e..498f8b8dfb 100644 --- a/test-fixture/Cargo.toml +++ b/test-fixture/Cargo.toml @@ -7,6 +7,10 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +description.workspace = true +keywords.workspace = true +categories.workspace = true +readme.workspace = true [lints] workspace = true diff --git a/test-fixture/src/sim/connection.rs b/test-fixture/src/sim/connection.rs index d05979cfca..58dd4bce23 100644 --- a/test-fixture/src/sim/connection.rs +++ b/test-fixture/src/sim/connection.rs @@ -196,7 +196,7 @@ pub struct ReachState { impl ReachState { /// Create a new instance that intends to reach the indicated state. #[must_use] - pub fn new(target: State) -> Self { + pub const fn new(target: State) -> Self { Self { target } } } @@ -225,7 +225,7 @@ pub struct SendData { impl SendData { #[must_use] - pub fn new(amount: usize) -> Self { + pub const fn new(amount: usize) -> Self { Self { remaining: amount, stream_id: None, @@ -307,7 +307,7 @@ pub struct ReceiveData { impl ReceiveData { #[must_use] - pub fn new(amount: usize) -> Self { + pub const fn new(amount: usize) -> Self { Self { remaining: amount } } diff --git a/test-fixture/src/sim/delay.rs b/test-fixture/src/sim/delay.rs index c8de66758c..788d10d7e7 100644 --- a/test-fixture/src/sim/delay.rs +++ b/test-fixture/src/sim/delay.rs @@ -44,7 +44,7 @@ impl RandomDelay { self.rng = Some(rng); } - pub fn next(&mut self) -> Duration { + pub fn next(&self) -> Duration { let mut rng = self.rng.as_ref().unwrap().borrow_mut(); let r = rng.random_from(0..self.max); self.start + Duration::from_nanos(r) diff --git a/test-fixture/src/sim/drop.rs b/test-fixture/src/sim/drop.rs index 6529a95d04..b528f47d30 100644 --- a/test-fixture/src/sim/drop.rs +++ b/test-fixture/src/sim/drop.rs @@ -28,7 +28,7 @@ impl Drop { /// random value between 0 and `max` (exclusive). If this value is less than /// `threshold` a value of `true` is returned. #[must_use] - pub fn new(threshold: u64, max: u64) -> Self { + pub const fn new(threshold: u64, max: u64) -> Self { Self { threshold, max, @@ -47,7 +47,8 @@ impl Drop { /// # Panics /// When this is invoked after test configuration has been torn down, /// such that the RNG is no longer available. - pub fn drop(&mut self) -> bool { + #[must_use] + pub fn drop(&self) -> bool { let mut rng = self.rng.as_ref().unwrap().borrow_mut(); let r = rng.random_from(0..self.max); r < self.threshold @@ -61,16 +62,14 @@ impl Node for Drop { // Pass any datagram provided directly out, but drop some of them. fn process(&mut self, d: Option, _now: Instant) -> Output { - if let Some(dgram) = d { + d.map_or(Output::None, |dgram| { if self.drop() { qtrace!("drop {}", dgram.len()); Output::None } else { Output::Datagram(dgram) } - } else { - Output::None - } + }) } } diff --git a/test-fixture/src/sim/rng.rs b/test-fixture/src/sim/rng.rs index 14b2240b9e..1ad36d2baf 100644 --- a/test-fixture/src/sim/rng.rs +++ b/test-fixture/src/sim/rng.rs @@ -79,12 +79,12 @@ impl Random { impl Default for Random { #[cfg(not(feature = "disable-random"))] fn default() -> Self { - Random::new(&neqo_crypto::random::<32>()) + Self::new(&neqo_crypto::random::<32>()) } #[cfg(feature = "disable-random")] // Use a fixed seed for a deterministic sequence of numbers. fn default() -> Self { - Random::new(&[1; 32]) + Self::new(&[1; 32]) } } diff --git a/test-fixture/src/sim/taildrop.rs b/test-fixture/src/sim/taildrop.rs index fc093e461d..953d720955 100644 --- a/test-fixture/src/sim/taildrop.rs +++ b/test-fixture/src/sim/taildrop.rs @@ -61,7 +61,7 @@ pub struct TailDrop { impl TailDrop { /// Make a new taildrop node with the given rate, queue capacity, and link delay. #[must_use] - pub fn new(rate: usize, capacity: usize, delay: Duration) -> Self { + pub const fn new(rate: usize, capacity: usize, delay: Duration) -> Self { Self { overhead: 64, rate, @@ -82,14 +82,14 @@ impl TailDrop { /// A tail drop queue on a 10Mbps link (approximated to 1 million bytes per second) /// with a fat 32k buffer (about 30ms), and the default forward delay of 50ms. #[must_use] - pub fn dsl_downlink() -> Self { - TailDrop::new(1_000_000, 32_768, Duration::from_millis(50)) + pub const fn dsl_downlink() -> Self { + Self::new(1_000_000, 32_768, Duration::from_millis(50)) } /// Cut uplink to one fifth of the downlink (2Mbps), and reduce the buffer to 1/4. #[must_use] - pub fn dsl_uplink() -> Self { - TailDrop::new(200_000, 8_192, Duration::from_millis(50)) + pub const fn dsl_uplink() -> Self { + Self::new(200_000, 8_192, Duration::from_millis(50)) } /// How "big" is this datagram, accounting for overheads.