Skip to content

Commit

Permalink
chore: Add a .rustfmt.toml and reformat (#1607)
Browse files Browse the repository at this point in the history
* chore: Add a `.rustfmt.toml` and reformat

Some of the settings in `.rustfmt.toml` require the nightly toolchain,
i.e, you need to `cargo +nightly fmt` to have them be used.

For VS Code, you can make is use the nightly `rustfmt` by default by adding
```
        "rust-analyzer.rustfmt.extraArgs": [
                "+nightly"
        ],
```
to your `settings.json` file.

Fixes #1417

* Normalize comment headings

* Spacing fixes
  • Loading branch information
larseggert authored Feb 1, 2024
1 parent f85f100 commit ca7d227
Show file tree
Hide file tree
Showing 161 changed files with 2,060 additions and 1,345 deletions.
7 changes: 7 additions & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
comment_width=100
wrap_comments=true

imports_granularity="Crate"
group_imports="StdExternalCrate"

format_code_in_doc_comments=true
41 changes: 18 additions & 23 deletions neqo-client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,6 @@
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(clippy::use_self)]

use common::IpTos;
use qlog::{events::EventImportance, streamer::QlogStreamer};

use mio::{net::UdpSocket, Events, Poll, PollOpt, Ready, Token};

use neqo_common::{self as common, event::Provider, hex, qlog::NeqoQlog, Datagram, Role};
use neqo_crypto::{
constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256},
init, AuthenticationStatus, Cipher, ResumptionToken,
};
use neqo_http3::{
self, Error, Header, Http3Client, Http3ClientEvent, Http3Parameters, Http3State, Output,
Priority,
};
use neqo_transport::{
CongestionControlAlgorithm, Connection, ConnectionId, ConnectionParameters,
EmptyConnectionIdGenerator, Error as TransportError, StreamId, StreamType, Version,
};

use std::{
cell::RefCell,
collections::{HashMap, VecDeque},
Expand All @@ -41,6 +22,22 @@ use std::{
time::{Duration, Instant},
};

use common::IpTos;
use mio::{net::UdpSocket, Events, Poll, PollOpt, Ready, Token};
use neqo_common::{self as common, event::Provider, hex, qlog::NeqoQlog, Datagram, Role};
use neqo_crypto::{
constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256},
init, AuthenticationStatus, Cipher, ResumptionToken,
};
use neqo_http3::{
self, Error, Header, Http3Client, Http3ClientEvent, Http3Parameters, Http3State, Output,
Priority,
};
use neqo_transport::{
CongestionControlAlgorithm, Connection, ConnectionId, ConnectionParameters,
EmptyConnectionIdGenerator, Error as TransportError, StreamId, StreamType, Version,
};
use qlog::{events::EventImportance, streamer::QlogStreamer};
use structopt::StructOpt;
use url::{Origin, Url};

Expand Down Expand Up @@ -1140,18 +1137,16 @@ mod old {
time::{Duration, Instant},
};

use url::Url;

use super::{qlog_new, KeyUpdateState, Res};
use mio::{Events, Poll};
use neqo_common::{event::Provider, Datagram, IpTos};
use neqo_crypto::{AuthenticationStatus, ResumptionToken};
use neqo_transport::{
Connection, ConnectionEvent, EmptyConnectionIdGenerator, Error, Output, State, StreamId,
StreamType,
};
use url::Url;

use super::{emit_datagram, get_output_file, Args};
use super::{emit_datagram, get_output_file, qlog_new, Args, KeyUpdateState, Res};

struct HandlerOld<'b> {
streams: HashMap<StreamId, Option<File>>,
Expand Down
22 changes: 22 additions & 0 deletions neqo-common/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ impl<'a> Decoder<'a> {
}

/// Skip n bytes.
///
/// # Panics
///
/// If the remaining quantity is less than `n`.
pub fn skip(&mut self, n: usize) {
assert!(self.remaining() >= n, "insufficient data");
Expand Down Expand Up @@ -90,7 +92,9 @@ impl<'a> Decoder<'a> {
}

/// Decodes an unsigned integer of length 1..=8.
///
/// # Panics
///
/// This panics if `n` is not in the range `1..=8`.
pub fn decode_uint(&mut self, n: usize) -> Option<u64> {
assert!(n > 0 && n <= 8);
Expand Down Expand Up @@ -198,7 +202,9 @@ pub struct Encoder {

impl Encoder {
/// Static helper function for previewing the results of encoding without doing it.
///
/// # Panics
///
/// When `v` is too large.
#[must_use]
pub const fn varint_len(v: u64) -> usize {
Expand All @@ -212,7 +218,9 @@ impl Encoder {
}

/// Static helper to determine how long a varint-prefixed array encodes to.
///
/// # Panics
///
/// When `len` doesn't fit in a `u64`.
#[must_use]
pub fn vvec_len(len: usize) -> usize {
Expand Down Expand Up @@ -261,7 +269,9 @@ impl Encoder {
}

/// Don't use this except in testing.
///
/// # Panics
///
/// When `s` contains non-hex values or an odd number of values.
#[must_use]
pub fn from_hex(s: impl AsRef<str>) -> Self {
Expand Down Expand Up @@ -291,7 +301,9 @@ impl Encoder {
}

/// Encode an integer of any size up to u64.
///
/// # Panics
///
/// When `n` is outside the range `1..=8`.
#[allow(clippy::cast_possible_truncation)]
pub fn encode_uint<T: Into<u64>>(&mut self, n: usize, v: T) -> &mut Self {
Expand All @@ -304,7 +316,9 @@ impl Encoder {
}

/// Encode a QUIC varint.
///
/// # Panics
///
/// When `v >= 1<<62`.
pub fn encode_varint<T: Into<u64>>(&mut self, v: T) -> &mut Self {
let v = v.into();
Expand All @@ -319,15 +333,19 @@ impl Encoder {
}

/// Encode a vector in TLS style.
///
/// # Panics
///
/// When `v` is longer than 2^64.
pub fn encode_vec(&mut self, n: usize, v: &[u8]) -> &mut Self {
self.encode_uint(n, u64::try_from(v.as_ref().len()).unwrap())
.encode(v)
}

/// Encode a vector in TLS style using a closure for the contents.
///
/// # Panics
///
/// When `f()` returns a length larger than `2^8n`.
#[allow(clippy::cast_possible_truncation)]
pub fn encode_vec_with<F: FnOnce(&mut Self)>(&mut self, n: usize, f: F) -> &mut Self {
Expand All @@ -343,15 +361,19 @@ impl Encoder {
}

/// Encode a vector with a varint length.
///
/// # Panics
///
/// When `v` is longer than 2^64.
pub fn encode_vvec(&mut self, v: &[u8]) -> &mut Self {
self.encode_varint(u64::try_from(v.as_ref().len()).unwrap())
.encode(v)
}

/// Encode a vector with a varint length using a closure.
///
/// # Panics
///
/// When `f()` writes more than 2^62 bytes.
#[allow(clippy::cast_possible_truncation)]
pub fn encode_vvec_with<F: FnOnce(&mut Self)>(&mut self, f: F) -> &mut Self {
Expand Down
3 changes: 1 addition & 2 deletions neqo-common/src/datagram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::net::SocketAddr;
use std::ops::Deref;
use std::{net::SocketAddr, ops::Deref};

use crate::{hex_with_len, IpTos};

Expand Down
3 changes: 1 addition & 2 deletions neqo-common/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::iter::Iterator;
use std::marker::PhantomData;
use std::{iter::Iterator, marker::PhantomData};

/// An event provider is able to generate a stream of events.
pub trait Provider {
Expand Down
3 changes: 2 additions & 1 deletion neqo-common/src/hrtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,12 +379,13 @@ impl Drop for Time {
not(all(any(target_os = "macos", target_os = "windows"), feature = "ci"))
))]
mod test {
use super::Time;
use std::{
thread::{sleep, spawn},
time::{Duration, Instant},
};

use super::Time;

const ONE: Duration = Duration::from_millis(1);
const ONE_AND_A_BIT: Duration = Duration::from_micros(1500);
/// A limit for when high resolution timers are disabled.
Expand Down
6 changes: 6 additions & 0 deletions neqo-common/src/incrdecoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ impl IncrementalDecoderUint {
}

/// Consume some data.
///
/// # Panics
///
/// Never, but this is not something the compiler can tell.
pub fn consume(&mut self, dv: &mut Decoder) -> Option<u64> {
if let Some(r) = &mut self.remaining {
Expand Down Expand Up @@ -87,7 +89,9 @@ impl IncrementalDecoderBuffer {
}

/// Consume some bytes from the decoder.
///
/// # Panics
///
/// Never; but rust doesn't know that.
pub fn consume(&mut self, dv: &mut Decoder) -> Option<Vec<u8>> {
let amount = min(self.remaining, dv.remaining());
Expand All @@ -109,7 +113,9 @@ pub struct IncrementalDecoderIgnore {

impl IncrementalDecoderIgnore {
/// Make a new ignoring decoder.
///
/// # Panics
///
/// If the amount to ignore is zero.
#[must_use]
pub fn new(n: usize) -> Self {
Expand Down
16 changes: 8 additions & 8 deletions neqo-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ pub mod qlog;
pub mod timer;
pub mod tos;

pub use self::codec::{Decoder, Encoder};
pub use self::datagram::Datagram;
pub use self::header::Header;
pub use self::incrdecoder::{
IncrementalDecoderBuffer, IncrementalDecoderIgnore, IncrementalDecoderUint,
};
pub use self::tos::{IpTos, IpTosDscp, IpTosEcn};

use std::fmt::Write;

use enum_map::Enum;

pub use self::{
codec::{Decoder, Encoder},
datagram::Datagram,
header::Header,
incrdecoder::{IncrementalDecoderBuffer, IncrementalDecoderIgnore, IncrementalDecoderUint},
tos::{IpTos, IpTosDscp, IpTosEcn},
};

#[must_use]
pub fn hex(buf: impl AsRef<[u8]>) -> String {
let mut ret = String::with_capacity(buf.as_ref().len() * 2);
Expand Down
5 changes: 2 additions & 3 deletions neqo-common/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@

#![allow(clippy::module_name_repetitions)]

use std::{io::Write, sync::Once, time::Instant};

use env_logger::Builder;
use lazy_static::lazy_static;
use std::io::Write;
use std::sync::Once;
use std::time::Instant;

#[macro_export]
macro_rules! do_log {
Expand Down
1 change: 1 addition & 0 deletions neqo-common/src/qlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct NeqoQlogShared {

impl NeqoQlog {
/// Create an enabled `NeqoQlog` configuration.
///
/// # Errors
///
/// Will return `qlog::Error` if cannot write to the new log.
Expand Down
23 changes: 15 additions & 8 deletions neqo-common/src/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::convert::TryFrom;
use std::mem;
use std::time::{Duration, Instant};
use std::{
convert::TryFrom,
mem,
time::{Duration, Instant},
};

/// Internal structure for a timer item.
struct TimerItem<T> {
Expand All @@ -21,10 +23,10 @@ impl<T> TimerItem<T> {
}

/// A timer queue.
/// This uses a classic timer wheel arrangement, with some characteristics that might be considered peculiar.
/// Each slot in the wheel is sorted (complexity O(N) insertions, but O(logN) to find cut points).
/// Time is relative, the wheel has an origin time and it is unable to represent times that are more than
/// `granularity * capacity` past that time.
/// This uses a classic timer wheel arrangement, with some characteristics that might be considered
/// peculiar. Each slot in the wheel is sorted (complexity O(N) insertions, but O(logN) to find cut
/// points). Time is relative, the wheel has an origin time and it is unable to represent times that
/// are more than `granularity * capacity` past that time.
pub struct Timer<T> {
items: Vec<Vec<TimerItem<T>>>,
now: Instant,
Expand All @@ -34,7 +36,9 @@ pub struct Timer<T> {

impl<T> Timer<T> {
/// Construct a new wheel at the given granularity, starting at the given time.
///
/// # Panics
///
/// When `capacity` is too large to fit in `u32` or `granularity` is zero.
pub fn new(now: Instant, granularity: Duration, capacity: usize) -> Self {
assert!(u32::try_from(capacity).is_ok());
Expand Down Expand Up @@ -109,7 +113,9 @@ impl<T> Timer<T> {
}

/// Asserts if the time given is in the past or too far in the future.
///
/// # Panics
///
/// When `time` is in the past relative to previous calls.
pub fn add(&mut self, time: Instant, item: T) {
assert!(time >= self.now);
Expand Down Expand Up @@ -241,9 +247,10 @@ impl<T> Timer<T> {

#[cfg(test)]
mod test {
use super::{Duration, Instant, Timer};
use lazy_static::lazy_static;

use super::{Duration, Instant, Timer};

lazy_static! {
static ref NOW: Instant = Instant::now();
}
Expand Down
12 changes: 7 additions & 5 deletions neqo-crypto/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(clippy::pedantic)]

use std::{
collections::HashMap,
env, fs,
path::{Path, PathBuf},
process::Command,
};

use bindgen::Builder;
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

const BINDINGS_DIR: &str = "bindings";
const BINDINGS_CONFIG: &str = "bindings.toml";
Expand Down
Loading

0 comments on commit ca7d227

Please sign in to comment.